unix timestamp to boost::posix_time::ptime

前端 未结 3 955
Happy的楠姐
Happy的楠姐 2021-01-17 13:42

I need to convert double with number of seconds since the epoch to ptime. I\'m prety sure there must be an easy way to do this, but I couldn\'t find anything. T

3条回答
  •  情歌与酒
    2021-01-17 14:27

    For a machine that has boost date/time compiled to the default level of microsecond resolution, try this:

    double ts = 1250524800.5;
    // Use floor() here if seconds are always positive.
    time_t secondsSinceEpoch = floor(ts);
    long microsecondsSinceSecond =
        floor((ts - static_cast(secondsSinceEpoch)) * 1000000);
    boost::posix_time::ptime result =
        boost::posix_time::from_time_t(secondsSinceEpoch);
    boost::posix_time::time_duration fractionalSeconds(0, 0, 0,
                                                       microsecondsSinceSecond);
    result += fractionalSeconds;
    cout << "Time stamp is " << result << endl;
    

    The output for this is "Time stamp is 2009-Aug-17 16:00:00.500000" on my linux box.

提交回复
热议问题