1

I have a function that takes a date, specified by its day, month and year and creates a std::time_t, and another function that takes a std::time_t and converts it to std::string. The thing is that I'm trying to work only with UTC dates. So, no other timezones must be considered for those two functions.

I have tried so far with:

std::time_t get_timestamp(unsigned day, unsigned month, unsigned year)
{
    std::tm t = {};
    t.tm_mday = day;
    t.tm_mon = month - 1;
    t.tm_year = year - 1900;
    t.tm_isdst = 0;

    return std::mktime(&t);
}

std::string get_date(std::time_t const& ts)
{
    std::ostringstream sso;
    sso << std::put_time(gmtime(&ts), "%Y-%m-%d %H:%M %Z");

    return sso.str();
}

std::time_t sample = get_timestamp("2017-06-01");
std::cout << get_date(sample) << std::endl;

But that piece of code prints 2017-05-31 23:00 GMT because mktime uses the current locale.

How can I change the first function definition to get the correct timestamp? I prefer not to work with additional libraries apart from boost and std.

ABu
  • 10,423
  • 6
  • 52
  • 103
  • @jmoon Ok that's right, GMT doesn't consider DST as UTC. Anyway, `mktime` considers the local timezone. – ABu Aug 15 '17 at 19:52
  • 1
    It is another library but [Howard's](https://stackoverflow.com/users/576911/howard-hinnant) library [date/tz](https://github.com/HowardHinnant/date) does this. Here is talk he has on it: https://www.youtube.com/watch?v=Vwd3pduVGKY&index=72&list=PLHTh1InhhwT7J5jl4vAhO1WvGHUUFgUQH – NathanOliver Aug 15 '17 at 19:53
  • Use the lower case `%z` (c++11) to get UTC offset (will be empty when offset is 0). – dlasalle Aug 15 '17 at 19:55
  • Both functions are one-liners using [Howard's](https://howardhinnant.github.io/date/date.html) header-only date lib. – Howard Hinnant Aug 15 '17 at 20:33

0 Answers0