获取指定时区的日期和时间

Get the date and time for specified timezone

本文关键字:时间 日期 取指 定时区 获取      更新时间:2023-10-16

我在英国有一台服务器(GMT+1(,我需要存储加拿大的日期(GMT-5(。这相对简单。

//gmt_operator, gmt_hr, gmt_min are all grabbed from a database
//These are the data extracted from GTM+5:00 for example.
//Get UTC+00:00 in seconds
time_t ltime;
time(&ltime);
//Add GMT offset
if (gmt_operator == '+')
ltime = ltime + (gmt_hr*60*60) + (gmt_min*60);
else if (gmt_operator  == '-')
ltime = ltime - (gmt_hr*60*60) - (gmt_min*60);
else
return NULL;
char buff[9];
struct tm * mydate= gmtime(&ltime);
strftime(buff, sizeof(buff), "%Y%m%d", today);
return buff;

在添加偏移量之前,我不能使用 tm 结构,因为如果我将 ltime 转换为 tm 结构而不是添加小时和分钟,我可能会溢出小时和分钟。这可以用 mktime(( 修复,但 mktime 也会转换为本地时间,这是我不想要的。

此解决方案存在一个小问题。时间还是1个小时。这是因为当前受影响的夏令时。函数 localtime(( 和 mktime(( 以某种方式抓取了这个,但这些函数只在服务器的本地时间抓取它,但我需要它用于指定的时间,如 GMT-5:00 或 GMT+2:00。

这对我来说是一个全新的领域,我希望能激发一些可能的解决方案。我希望这不是重复的,但我还没有找到类似的问题。

到目前为止,您的代码是正确的。"GMT-5:00"和"GMT+2:00"的含义始终相同,与DST(夏令时又名夏令时(无关。

换句话说,DST 已经需要包含在这些规范中。

例如,在中欧,你不能只说"GMT+01"。您有 CET 和 CEST,这意味着"GMT+01"或"GMT+02"。