【发布时间】:2022-02-03 09:38:52
【问题描述】:
我正在尝试计算由两个整数表示的给定日期和时间的 Unix 时间,例如
testdate1 = 20060711(2006 年 7 月 11 日)
testdate2 = 4(00:00:04,午夜后 4 秒)
在我当地时区以外的时区。为了计算 Unix 时间,我将 testdate1、testdate2 输入到我改编自 Convert date to unix time stamp in c++ 的函数中
int unixtime (int testdate1, int testdate2) {
time_t rawtime;
struct tm * timeinfo;
//time1, ..., time6 are external functions that extract the
//year, month, day, hour, minute, seconds digits from testdate1, testdate2
int year=time1(testdate1);
int month=time2(testdate1);
int day=time3(testdate1);
int hour=time4(testdate2);
int minute=time5(testdate2);
int second=time6(testdate2);
time ( &rawtime );
timeinfo = localtime ( &rawtime );
timeinfo->tm_year = year - 1900;
timeinfo->tm_mon = month - 1;
timeinfo->tm_mday = day;
timeinfo->tm_hour = hour;
timeinfo->tm_min = minute;
timeinfo->tm_sec = second;
int date;
date = mktime(timeinfo);
return date;
}
我从主代码调用的
using namespace std;
int main(int argc, char* argv[])
{
int testdate1 = 20060711;
int testdate2 = 4;
//switch to CET time zone
setenv("TZ","Europe/Berlin", 1);
tzset();
cout << testdate1 << "\t" << testdate2 << "\t" << unixtime(testdate1,testdate2) << "\n";
return 0;
}
通过给定的示例,我得到unixtime(testdate1,testdate2) = 1152572404,根据
https://www.epochconverter.com/timezones?q=1152572404&tz=Europe%2FBerlin
是 1:00:04 am CEST,但我希望这是 0:00:04 CEST。
如果我选择testdate1、testdate2,代码似乎运行良好,在该testdate2 中没有遵守夏令时。例如,通过设置testdate1 = 20060211 来简单地将月份设置为二月,而其他所有内容都保持不变。这给
unixtime(testdate1,testdate2) = 1139612404,根据需要对应于 CET 中的 hh:mm:ss = 00:00:04。
我的印象是setenv("TZ","Europe/Berlin", 1) 应该在适用时考虑 DST,但也许我弄错了。 TZ 能否解释 testdate1、testdate2 以解释夏令时?
有趣的是,我有一个 python 代码通过os.environ['TZ'] = 'Europe/Berlin' 更改本地时间来执行相同的任务。在这里我没有问题,因为它似乎计算了正确的 Unix 时间,而不管 DST/非 DST。
【问题讨论】: