【发布时间】:2014-09-28 06:12:45
【问题描述】:
我正在用 c++ 编写一个 impala udf,当在 yyyyMMdd 中提供日期时,它会获得一年中的一周。但似乎找不到在 c++ 中将 yyyyMMdd 转换为一年中的一周的方法。在java中我可以你日历,但是如何在c ++中进行。
TIA
【问题讨论】:
我正在用 c++ 编写一个 impala udf,当在 yyyyMMdd 中提供日期时,它会获得一年中的一周。但似乎找不到在 c++ 中将 yyyyMMdd 转换为一年中的一周的方法。在java中我可以你日历,但是如何在c ++中进行。
TIA
【问题讨论】:
您可以只使用来自<ctime> 的std::mktime。示例:
std::tm date={};
date.tm_year=2014-1900;
date.tm_mon=9-1;
date.tm_mday=28;
std::mktime(&date);
调用后,date.tm_wday 被调整(0=星期日)。 date.tm_yday 也进行了调整。
要获得一年中的一周,请使用:(date.tm_yday-date.tm_wday+7)/7
此计算返回第一个完整周的 1(即一年中的第一周,其中包括星期日开始的年份的 1 月 1 日); 0 表示第一周的天数。
【讨论】:
我回答了这个here,但为了完整起见,我也在这里重复一下:
使用来自howardhinnant.github.io/iso_week.html 的iso_week.h:
#include <iostream>
#include "iso_week.h"
int main() {
using namespace iso_week;
using namespace std::chrono;
// Get the current time and floor to convert to the sys_days:
auto today = floor<days>(system_clock::now());
// Convert from sys_days to iso_week::year_weeknum_weekday format
auto yww = year_weeknum_weekday{today};
// Print current week number of the year
std::cout << "The current week of " << yww.year() << " is: "
<< yww.weeknum() << std::endl;
// Set any day
auto any_day = 2014_y/9/28;
// Get week of `any_day`
std::cout << "The week of " << any_day.year() << " on `any day` was: "
<< any_day.weeknum() << std::endl;
}
给出输出:
The current week of 2019 is: W18
The week in 2014 on `any day` was: W09
【讨论】:
使用 boost::date 库。简单易用。
【讨论】: