5

我有一个包含本地日期/时间的字符串,我需要将其转换为 time_t 值(以 UTC 为单位) - 我一直在尝试这个:

char* date = "2009/09/01/00";
struct tm cal = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL};
strptime(date, "%Y/%m/%d/%H", &cal);
time_t t = mktime(&cal);

但是如果字符串被解析为 UTC 而不是本地时间,我得到的 time_t 值是我期望的值。也许我误解了 strptime 应该做什么,但是在 9 月 1 日我的时区(英国)中,我们使用的是 BST(即 UTC + 1 小时),所以我希望我最终得到的值比 UTC 早 1 小时.

有没有办法将字符串解释为本地时间,自动考虑到该日期有效的 UTC 偏移量?请注意,我需要 time_t 值而不是 struct tm,在上面的示例中,我希望 time_t 值对应于 2009-09-01 01:00:00 GMT

4

3 回答 3

6

您可以使用mktime来解释本地时区中的 struct tm。这样做时,请小心设置tm_isdst标志。夏季为 0,冬季为 1,为 -1 表示mktime确定。这是一些示例代码:

void main()
{
    char* date = "2009/09/01/00";
    struct tm cal = {};
    // Read string into struct tm
    strptime(date, "%Y/%m/%d/%H", &cal);
    // Tell mktime to figure out the daylight saving time
    cal.tm_isdst = -1;
    printf("%20s: %s", "Before mktime", asctime(&cal));
    // Convert struct tm to time_t
    time_t t = mktime(&cal);
    // Convert time_t to localtime
    struct tm localcal = *localtime(&t);
    printf("%20s: %s", "Local time", asctime(&localcal));
    printf("%20s: %i\n", "Local DST", localcal.tm_isdst);
    // Convert time_t to GMT
    struct tm gmcal = *gmtime(&t);
    printf("%20s: %s", "GM time", asctime(&gmcal));
    printf("%20s: %i\n", "GM DST", gmcal.tm_isdst);
}

这打印(我住在 GMT+1,现在是冬天):

   Before mktime: Tue Sep  1 00:00:00 2009
      Local time: Tue Sep  1 00:00:00 2009
       Local DST: 1
         GM time: Mon Aug 31 22:00:00 2009
          GM DST: 0

看起来像mktime根据当前的夏令时转换 9 月的日期。现在是十一月,所以实际上是一个小时的休息时间。我还没有找到纠正的方法。

于 2009-11-19T17:05:38.280 回答
0

这是我的版本,使用tm_gmtoff. 希望图书馆能照顾夏时制......

#define _BSD_SOURCE
#define _XOPEN_SOURCE
#include <stdio.h>
#include <time.h>

int gmtoffset(void) {
  struct tm *dummy;
  time_t t = 0;
  dummy = localtime(&t);
  return dummy->tm_gmtoff; /* _BSD_SOURCE */
}

int main(void) {
  int off;
  const char *date = "2009/09/01/00";
  struct tm cal = {0};
  time_t t;

  off = gmtoffset();

  strptime(date, "%Y/%m/%d/%H", &cal); /* _XOPEN_SOURCE */
  t = mktime(&cal);
  printf("t     --> %s", ctime(&t)); /* ctime includes a final '\n' */
  t -= off;
  printf("t-off --> %s", ctime(&t));
  return 0;
}
$ /usr/bin/gcc ptime.c
$ ./a.out
t --> 2009 年 9 月 1 日星期二 01:00:00
t-off --> 2009 年 9 月 1 日星期二 00:00:00
于 2009-11-19T19:02:35.753 回答
0

多亏了 Andomar,我想我现在已经破解了它——这段代码可以满足我的需要,并且无论当前的 DST 状态如何,它似乎都能正常工作(我更改了我的电脑上的时钟来检查这个):

#include <time.h>
#include <assert.h>

time_t parseLocalDate(char* date){
    struct tm cal = {0, 0, 0, 0, 0, 0, 0, 0, -1, 0, NULL};
    strptime(date, "%Y/%m/%d/%H", &cal);
    return mktime(&cal);
}

int main(int argc, char *argv[]){
 // DST is effect, Local Time = GMT+1
    assert(1251759600 == parseLocalDate("2009/09/01/00")); // Mon, 31 Aug 2009 23:00:00 GMT
    assert(1254351600 == parseLocalDate("2009/10/01/00")); // Wed, 30 Sep 2009 23:00:00 GMT
 // DST not in effect, Local Time = GMT
    assert(1257033600 == parseLocalDate("2009/11/01/00")); // Sun, 01 Nov 2009 00:00:00 GMT
}
于 2009-11-20T08:49:35.290 回答