I'm writing a impala udf in c++ which gets week of year when provided with date in yyyyMMdd. But could not seem to find way to convert yyyyMMdd to week of year in c++. In java I can you Calendar, but how to go about it in c++.
TIA
I'm writing a impala udf in c++ which gets week of year when provided with date in yyyyMMdd. But could not seem to find way to convert yyyyMMdd to week of year in c++. In java I can you Calendar, but how to go about it in c++.
TIA
You can just use std::mktime
from <ctime>
. Example:
std::tm date={};
date.tm_year=2014-1900;
date.tm_mon=9-1;
date.tm_mday=28;
std::mktime(&date);
After the call, date.tm_wday is adjusted (0=Sunday). date.tm_yday is also adjusted.
To get the week into the year, use: (date.tm_yday-date.tm_wday+7)/7
This calculation returns 1 for the first full week (namely, first week with a Sunday in it in the year, including Jan 1 in years that start with Sunday); and 0 for days in the first partial week.
I answered this here, but for the sake of completeness, I will repeat it here too:
Use iso_week.h
from howardhinnant.github.io/iso_week.html :
#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;
}
which gives the output:
The current week of 2019 is: W18
The week in 2014 on `any day` was: W09