将毫秒UTC转换为人类可读日期时间 [英] Converting millisecond UTC to Human Readable Date_Time

查看:194
本文介绍了将毫秒UTC转换为人类可读日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚如何使用boost :: date_time执行转换。
我想将从Unix纪元(1970年1月1日00:00)测量的毫秒值转换为人类可读的字符串 - 例如: 2/13/2012 15:20: 11 将是理想的。

I'm struggling to figure out how to preform a conversion with boost::date_time. I want to convert a millisecond value measured from the Unix epoch (00:00, Jan 1, 1970) to a human readable string - something like: 2/13/2012 15:20:11 would be ideal.

我试过一些std C ++ /提升建议,我看到,但还没有运气。这里是我使用的代码:

I've tried some std C++ / boost suggestions I've seen but not had any luck just yet. Here is the code I use:

    long long ticksFromEpoch = 1329117220501;

    std::time_t tt = static_cast<time_t>(ticksFromEpoch);

    boost::posix_time::ptime dt = boost::posix_time::from_time_t(tt);

    // Create a time_zone_ptr for the desired time zone and use it to create a local_date_time
    boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone("UTC"));
    boost::local_time::local_date_time dt_with_zone(dt, zone);

    std::stringstream strm;

    strm.imbue(std::locale(std::cout.getloc(), new boost::local_time::local_time_facet("%Y-%m-%d %H:%M:%S"))); // 15:14
    strm << dt_with_zone;

    // Print the stream's content to the console
    std::cout << strm.str() << std::endl;

输出为: 2032-07-01 20:20:37 这显然不正确。我怀疑我不是正确构建 ticksFromEpoch变量,但我不知道为什么。任何人都可以指向正确的方向?任何帮助是非常感谢!!

The output is: 2032-07-01 20:20:37 which is clearly incorrect. I suspect that I'm not constructing the ticksFromEpoch variable correctly but I'm not sure why. Can anyone point me in the right direction? Any help is much appreciated!!

推荐答案

time_t 时代,而不是毫秒。
如果你不关心毫秒,你应该能够这样做:

time_t is usually seconds since "the epoch", rather than milliseconds. If you dont care about milliseconds you should be able to do this:

std::time_t tt = static_cast<time_t>(ticksFromEpoch/1000)

如果您关心毫秒,您可以将它们添加回结束(对于像12:00:00.001 AM这样的时间来说很麻烦)

If you do care about milliseconds you can either add them back in at the end (which is tricky to get right for times like 12:00:00.001 AM )

或者你需要走另一条路线。您可能需要使用这样的:(未测试)

Or you'll need to go another route. You may need to use something like this: (untested)

boost::posix_time::ptime t2(
  date(1970,Jan,1),  //The epoch
  boost::posix_time::seconds( ticksFromEpoch / 1000 ) + // Number of seconds
  boost::posix_time::microseconds( ticksFromEpoch % 1000)  // And the micros too.
  );

这篇关于将毫秒UTC转换为人类可读日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆