【问题标题】:c Specific Date to Timec 特定日期到时间
【发布时间】:2014-04-20 21:38:59
【问题描述】:

我想在 C 中从特定日期转换为秒。例如,如果我给出 12/25/2015,它将转换为秒。 这是我发现的将当前日期转换为秒的程序。但我想从特定日期转换为秒。

time_t timer;
  struct tm y2k;
  double seconds;

  y2k.tm_hour = 0;   y2k.tm_min = 0; y2k.tm_sec = 0;
  y2k.tm_year = 0; y2k.tm_mon = 0; y2k.tm_mday = 1;

  time(&timer);  

  seconds = difftime(timer,mktime(&y2k));

  printf ("%.f ", seconds); 

【问题讨论】:

  • C++ 还是 C?您的代码似乎是 C,而不是 C++

标签: c date seconds time-t


【解决方案1】:

mktime() 的结果是自 1970 年 1 月 1 日午夜 00:00:00 UTC 以来的秒数(给定或取几闰秒)。

这也称为Unix time

【讨论】:

  • 我不知道如何轻松获得比 Unix Time 提供的更精确的值。
【解决方案2】:

阅读 tm 结构的手册页 (http://www.cplusplus.com/reference/ctime/tm/)。 2015 年 12 月 25 日,

y2k.tm_year = 2015 - 1900; /* Starts from 1900 */
y2k.tm_mon = 12 - 1; /* Jan = 0 */
y2k.tm_mday = 15;

另外,要打印双精度,请使用 %lf。如果只使用 %f,可能无法得到想要的结果。

【讨论】:

  • "%f" 或 "%lf" 在 printf() 中具有完全相同的含义,因为 C99(它们在 scanf() 中有所不同)。
【解决方案3】:

您可能还会发现 strptime(3) 很有用。

#include <stdio.h>
#include <string.h>
#include <time.h>

int
main(int ac, char *av[])
{
    char format[] = "%m/%d/%y";
    char input[] = "12/25/15";
    char buf[256];
    struct tm tm;

    memset(&tm, 0, sizeof tm);

    if (strptime(input, format, &tm) == NULL) {
         fputs("strptime failed\n", stderr);
         return 1;
    }

    strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);

    printf("reformatted: %s; as time_t: %ld\n", buf, mktime(&tm));

    return 0;
}

【讨论】:

    猜你喜欢
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 2021-04-07
    • 2019-06-19
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多