c - 带有时区偏移量的 c 中的 strptime

标签 c timezone getdate strptime timezone-offset

我无法找到一种方法来从如下字符串中解析出时区: “2011 年 9 月 1 日星期四 09:06:03 -0400 (EDT)”

在我的程序的较大方案中,我需要做的是接收一个 char* 并将其转换为 time_t。 以下是我编写的一个简单测试程序,用于尝试弄清楚 strptime 是否完全考虑了时区,但似乎没有(当此测试程序执行时,所有打印的数字都相同,而它们应该不同)。建议?

我还尝试使用 GNU getdate 和 getdate_r,因为对于可能灵活的格式来说,这看起来是一个更好的选择,但我从编译器收到了“隐式函数声明”警告,暗示我没有包含正确的库。还有什么我应该#include-ing 来使用 getdate 吗?

#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>

#ifndef __USE_XOPEN
#define __USE_XOPEN
#endif
#include <time.h>

int main (int argc, char** argv){

char *timestr1, *timestr2, *timestr3;
struct tm time1, time2, time3;
time_t timestamp1, timestamp2, timestamp3;

timestr1 = "Thu, 1 Sep 2011 09:06:03 -0400 (EDT)"; // -4, and with timezone name
timestr2 = "Thu, 1 Sep 2011 09:06:03 -0000"; // -0

strptime(timestr1, "%a, %d %b %Y %H:%M:%S %Z", &time1); //includes UTC offset
strptime(timestr2, "%a, %d %b %Y %H:%M:%S %Z", &time2); //different UTC offset
strptime(timestr1, "%a, %d %b %Y %H:%M:%S", &time3); //ignores UTC offset

time1.tm_isdst = -1;
timestamp1 = mktime(&time1);
time2.tm_isdst = -1;
timestamp2 = mktime(&time2);
time3.tm_isdst = -1;
timestamp3 = mktime(&time3);

printf("Hello \n");
printf("%d\n%d\n%d\n", timestamp1, timestamp2, timestamp3);
printf("Check the numbers \n");
return 0;
}

最佳答案

在 MacOS X (10.7.1) 上,strptime(3) 手册页中列出的“错误”之一是:

The %Z format specifier only accepts time zone abbreviations of the local time zone, or the value "GMT". This limitation is because of ambiguity due to of the over loading of time zone abbreviations. One such example is EST which is both Eastern Standard Time and Eastern Australia Summer Time.

前段时间,我写了一对命令 - timestamp(1989 年 5 月修订版 1.1)和 strptime(2007 年 7 月修订版 1.1)。这些是对 strftime()strptime() 函数的相对较薄的覆盖。

在 MacOS X 上运行它们,我得到:

$ strptime -T '%Y-%m-%dT%H:%M:%S %Z' 2011-09-08T21:00:00PDT
1315540800 = 2011-09-08T21:00:00PDT
$ timestamp 1315540800
1315540800 = Thu Sep 08 21:00:00 2011
$ timestamp -u 1315540800
1315540800 = Fri Sep 09 04:00:00 2011
$ strptime -T '%Y-%m-%dT%H:%M:%S %Z' 2011-09-08T21:00:00GMT
1315515600 = 2011-09-08T21:00:00GMT
$ timestamp 1315515600
1315515600 = Thu Sep 08 14:00:00 2011
$ timestamp -T '%Y-%m-%dT%H:%M:%S %z' 1315515600
1315515600 = 2011-09-08T14:00:00 -0700
$

我在 US/Pacific(或 America/Los_Angeles,或太平洋夏令时;UTC-07:00),所以这些命令显示的是(如手册页所述)strptime() 识别 PDT 和 GMT 并为每个给出适当的答案。 timestamp-u 选项指示“打印 UTC(又名 GMT)时间”而不是本地时间。 UTC 的晚上 9 点确实是 PDT 的下午 2 点。

如果您想要源代码,请联系我 - 查看我的个人资料。

关于c - 带有时区偏移量的 c 中的 strptime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7325571/

相关文章:

c - -32767 为什么这个函数会返回?

c - 是否有解析 POSIX 时区并验证它的函数?

sql - 设置日期是从 getdate() 的一年开始吗?

c - Realloc 在 while 循环中不起作用

c - Tee 命令将输出保存在 txt 文件中

c - 在 C 函数中可以有未使用的参数吗?

php - 日期时间格式和时区

java - 如何向来自不同时区的用户显示日期(没有时间元素)?

sql-server - 在 View 中使用调用 GETDATE() 的函数是否始终比直接使用 GETDATE() 提供更差的性能?

powershell - 在 PowerShell 中复制文件并将日期添加到其名称