历史时间到 GMT\UTC(带 DST)
类似于:
这次我的场景是: 我需要将格式为“2011061411322100”的一些字符串时间转换为 GMT。问题是时间来自另一台电脑并且是历史时间。所以我没有实时获取时间,所以我不能简单地从我的代码运行的盒子上的当地时间获取 GMT。
时间代表开始和结束时间。如果我的代码在时间更改期间运行,则时间更改将应用到我获取时间的远程盒子上。因此,如果开始时间和结束时间之间发生变化,则结束时间将被偏移。
我假设我必须首先转换为 tm:
// add to tm struct
tm tmTime;
tmTime.tm_hour = hour;
tmTime.tm_min = min;
tmTime.tm_sec = sec;
tmTime.tm_mday = day;
tmTime.tm_mon = (month-1);
tmTime.tm_year = (year - 1900);
然后转换为 time_t
time_t tmInTime_t = mktime( &tmTime );
然后使用 gmtime:
struct tm *gmt = gmtime( &tmInTime_t );
如果开始和结束之间发生时间变化,这仍然会导致较大的增量。我该如何修复? 我需要设置.tm_isdst吗?我怎么知道要设置什么?
Similar to:
Convert historical time to GMT
This time my scenario is:
I need to convert some string times in the format "2011061411322100" into GMT. The problem is that the times are coming from another PC and is a historical time. So I am not getting the times in real time so I cannot simply get the GMT from the local time on the box that my code is running.
The times represent Start and End times. If my code is running during a time change, the time change will bre applied on the remote box where I am getting the times. So if the change happens betwwen the start and end time, then the end time will be offset.
I assume I must first convert to tm:
// add to tm struct
tm tmTime;
tmTime.tm_hour = hour;
tmTime.tm_min = min;
tmTime.tm_sec = sec;
tmTime.tm_mday = day;
tmTime.tm_mon = (month-1);
tmTime.tm_year = (year - 1900);
Then convert to time_t
time_t tmInTime_t = mktime( &tmTime );
Then use gmtime:
struct tm *gmt = gmtime( &tmInTime_t );
This will still cause large delta if time change happens between start and end. How do I fix?
Do I need to set .tm_isdst? How do I know what to set to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您绝对必须知道源数据上的参考时区。简单地说这是源计算机上的当地时间并不能提供足够的信息。
考虑一下(举一个例子):2007 年美国的 DST 规则发生了变化,跨越该范围的任何日期计算都必须考虑到这一点。当你开始处理跨越政治边界的时区时,事情会变得更加复杂。
http://www.boost.org/doc/libs/1_47_0 /doc/html/date_time.html
是一个用 C++ 编写的强大时间/日期库的示例,适用于大多数平台。它将允许您对日期和时间执行各种“算术”运算。它还包括对 TZ 数据库的支持,这将允许您对跨越时区规则更改的日期时间执行操作。
You ABSOLUTELY must know what the reference timezone was on the source data. Simply saying it was local time on the source machine doesn't provide enough info.
Consider (for one example out of many): The DST rules changed in the US in 2007, and any date calculations spanning across that range must take that into account. When you start dealing with timezones across political borders things get vastly more complicated.
http://www.boost.org/doc/libs/1_47_0/doc/html/date_time.html
is an example of a robust time/date library written in C++ and works on most platforms. It will allow you to perform various 'arithmetic' operations on dates and times. It also includes support for the TZ database, which will allow you to perform operations on datetimes spanning timezone rule changes.