如何知道Solaris上GMT和C 的本地时间的差异

How to know the difference of GMT and local time in C++ on Solaris?

本文关键字:时间 Solaris 何知道 GMT      更新时间:2023-10-16

我喜欢根据秒数计算本地时间(某些时区)和GMT的差异。我使用以下代码段:

time_t now = time(0); // GMT
time_t gmnow = mktime(gmtime(&now)); // further convert to GMT presuming now in local
time_t diff = gmnow - now;

但是,我遇到了错误的区别。我在这里要做的是将当前时间作为GMT贯穿时间(0)。然后假定这是当地时间,我致电GMTime添加GMT差异因子并使用MKTime重新转换为当地时间。这应该显示GMT和我的时区的差异,但它显示出1小时的额外差异(日光节省)。

例如,我目前的时间是THU MAR 13 04:54:45 EDT 2014当我获得GMT的当前时间时,应该是:THU 3月13日08:55:34 GMT 2014考虑到这是当前的时间,如果我打电话给GMTime,这应该进一步进行,重新转换应该给我4小时的区别,但我的区别为5小时。

GMTime使用情况错误吗?另外,我如何知道当前时区以及日光节省的时间?

得到它!

以下代码段将解决此问题:

time_t now = time(0); // UTC
time_t diff;
struct tm *ptmgm = gmtime(&now); // further convert to GMT presuming now in local
time_t gmnow = mktime(ptmgm);
diff = gmnow - now;
if (ptmgm->tm_isdst > 0) {
    diff = diff - 60 * 60;
} 

诀窍是检查TM_ISDST标志,如果适用,如果设置,请多调整一个小时以diff这有效。感谢您的时间。

这可以以正确的方式处理它:

time_t t = time (NULL);
tm * srTM = localtime(&t);
setenv("TZ", "GMT0",1); //Change your timezone to GMT
time_t t2 = mktime(srTM);  
diff = difftime(t2,t);
setenv("TZ", "CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00", 1); //Reset your timezone to correct one (here CET)