1

I'm using boost::date_time and I got a time_t, that have been generated by a library using the time() function from the C standard library.

I'm looking for a way get a local time from that time_t. I'm reading the documentation and can't find any way to do this without providing a time zone, that I don't know about because it's dependant on the machine's locale, and I can't find any way to get one from it.

What am I missing?

Klaim
  • 67,274
  • 36
  • 133
  • 188

2 Answers2

13

boost::posix_time::from_time_t()

#include <ctime>
#include <ostream>
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>

boost::posix_time::ptime local_ptime_from_utc_time_t(std::time_t const t)
{
    using boost::date_time::c_local_adjustor;
    using boost::posix_time::from_time_t;
    using boost::posix_time::ptime;
    return c_local_adjustor<ptime>::utc_to_local(from_time_t(t));
}

int main()
{
    using boost::posix_time::to_simple_string;
    using boost::posix_time::from_time_t;

    std::time_t t;
    std::time(&t); // initalize t as appropriate
    std::cout
        << "utc:   "
        << to_simple_string(from_time_t(t))
        << "\nlocal: "
        << to_simple_string(local_ptime_from_utc_time_t(t))
        << std::endl;
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • -1 : I said a LOCAL time. I'm already using this and it's wrong because it don't take account of the locale time. For example, I'm in GMT+2, so when I do time() it gives me GMT+0 and I have to add two hours to get the corret time. I don't even know where will be the user of the app and need to take the local time. – Klaim May 26 '11 at 19:05
  • 1
    @Klaim : Edited to demonstrate a complete example (I figured converting from utc to local was the obvious part and you didn't know how to get a `ptime` from a `std::time_t`). – ildjarn May 26 '11 at 19:32
0

For this task, I'd ignore boost::date_time and just use localtime (or localtime_r, if available) from the standard library.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Ok so I used this and built a boost::posix_time::ptime with it to manipulate the time once localized. Thanks it works! – Klaim May 26 '11 at 19:17
  • 3
    Aren't boost date/time objects supposed to be thread-safe ? Localtime isn't really an alternative in that case. – Michael Feb 01 '16 at 14:40
  • 1
    @Michael: Yes, thread safety would be one of the reasons to use "`localtime_r`, if available". – Jerry Coffin Oct 27 '20 at 16:00