简体   繁体   English

转换毫秒到time_t

[英]Convert milliseconds to time_t

I have the number of milliseconds starting from 2004 to a specific date. 我具有从2004年到特定日期的毫秒数。 I want to convert this to time_t to display it with ctime()? 我想将其转换为time_t以与ctime()一起显示吗?

Perhaps there is another method to visualize the date by this milliseconds timestamp, does anyone have one? 也许还有另一种方法可以通过这种毫秒的时间戳可视化日期,有人吗?

Assuming that by “starting from 2004” you mean “starting from 2004 at 00:00 UTC”, then 假设“从2004年开始”是指“从2004年世界标准时间00:00开始”,那么

time_t time = 1072915200 + millis / 1000;

Beware that ctime() will display the result in local time instead of UTC. 请注意, ctime()将以本地时间而不是UTC显示结果。

time_t only has an accuracy of one second. time_t的精度仅为一秒。 If this is ok for you, you can calculate the time_t value for 2004-01-01 using mktime() and add it to your time-value in seconds. 如果您认为可以,则可以使用mktime()计算2004-01-01的time_t值,并将其添加到以秒为单位的时间值中。

struct tm tp;
memset(&tp, 0, sizeof(tp));
tp.tm_mday = 1;
tp.tm_mon = 0;
tp.tm_year = 2004 - 1900;
time_t offset = mktime(&tp);

time_t realtime = offset + yourtime / 1000;

printf("%s", ctime(&realtime));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM