【问题标题】:strtoul to convert from String date ("03/10/2013 14:01:00") to time_tstrtoul 从字符串日期(“03/10/2013 14:01:00”)转换为 time_t
【发布时间】:2013-11-01 17:19:29
【问题描述】:

我不明白,为什么这不起作用? PS:这段代码是从某个谷歌上找到的!

问题:我不知道为什么它应该起作用?这是否也考虑时区?!

  1 #include<stdio.h>
  2 #include <stdlib.h>
  3 #include <string>
  4 #include <time.h>
  5 int main()
  6 {
  7     std::string text("10/10/2013 14:01:00");
  8     const char* nptr = text.c_str();
  9     char* endptr = NULL;
 10     time_t seconds_from_epoch = strtoul(nptr, &endptr, 0);
 11     if (secs != 0)
 12         printf("Secs: %ld\n", secs);
 13     if (*nptr != '\0' && endptr && *endptr  == '\0') {
 14         printf("Secs: %ld\n", secs);
 15     } else {
 16         printf("Unable to convert\n");
 17     }
 18 }

【问题讨论】:

    标签: c time-t strtol


    【解决方案1】:

    这是错误的假设。

    我就是这样做的:

     21     printf("************************\n");
     22     int day, month, yr, hr, min, sec, tzone;
     23     char* more = (char *)nptr;
     24     month = strtol(more, &more, 10);
     25     day = strtol(more+1, &more, 10);
     26     yr = strtol(more+1, &more, 10);
     27     hr = strtol(more+1, &more, 10);
     28     min = strtol(more+1, &more, 10);
     29     sec = strtol(more+1, &more, 10);
     30     tzone = strtol(more+1, &more, 10);
     31 
     32     printf("Month: %d, Day: %d, Year: %d, Hour: %d, Min: %d, Sec: %d, Tzone:     %d\n", 
     33             month, day, yr, hr, min, sec, tzone);
    

    然后可以使用 struct tm 和 mktime。

    【讨论】:

    • strptime 是你的朋友。
    • 对,我希望 inbuild 可以直接转换为 time_t 或 tm。不管怎样,它奏效了!
    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2020-03-04
    • 1970-01-01
    相关资源
    最近更新 更多