2

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

Pravin Gadakh
  • 603
  • 1
  • 9
  • 19

3 Answers3

6

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.

H Walters
  • 2,634
  • 1
  • 11
  • 13
  • @H Walters: tm_wday gives day since sunday but what I want is week number in that year. Just like Calendar.week_of_year in java. – Pravin Gadakh Sep 28 '14 at 06:52
  • I'm not sure if you can do "just like" week_of_year, in that I'm not sure it's easy to grab locale preferences. But mktime will also fill in tm_yday for you so, e.g., (date.tm_yday-date.tm_wday)/7 would be a basis count (mind border cases--like the actual first week). – H Walters Sep 28 '14 at 07:07
1

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
Remis
  • 571
  • 4
  • 12
0

Use boost::date library.It's simple and easy to use.

wuqiang
  • 634
  • 3
  • 8