VMi*_*lls 5 c timezone getdate strptime timezone-offset
我很难找到一种方法来解析时区,如下所示:"星期四,2011年9月1日09:06:03 -0400(美国东部时间)"
我需要在我的程序的更大方案中做的是接受char*并将其转换为time_t.以下是我编写的一个简单的测试程序,试图找出strptime是否完全考虑时区,并且它似乎不是(当这个测试程序执行时,所有打印的数字在它们应该不同时是相同的).建议?
我也尝试使用GNU getdate和getdate_r,因为对于可能灵活的格式来说,这似乎是一个更好的选择,但是我从编译器得到了一个"隐式函数声明"警告,暗示我没有包含正确的库.还有其他我应该#include使用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;
}
Run Code Online (Sandbox Code Playgroud)
在 MacOS X (10.7.1) 上,手册页中列出的“错误”之一strptime(3)是:
%Z 格式说明符仅接受本地时区的时区缩写或值“GMT”。此限制是由于时区缩写过多而导致歧义。其中一个例子是 EST,它既是东部标准时间又是澳大利亚东部夏令时间。
前段时间,我写了一对命令——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
$
Run Code Online (Sandbox Code Playgroud)
我在美国/太平洋地区(或美洲/洛杉矶,或太平洋夏令时;UTC-07:00),所以这些命令显示的是(如手册页所述),strptime()识别 PDT 和 GMT 并为每个时间提供适当的答案。该-u选项timestamp指示“打印 UTC(又名 GMT)时间”而不是本地时间。UTC 晚上 9 点实际上是 PDT 下午 2 点。
如果您想要来源,请联系我 - 请参阅我的个人资料。
| 归档时间: |
|
| 查看次数: |
8567 次 |
| 最近记录: |