Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c具体日期至时间_C_Date_Seconds_Time T - Fatal编程技术网

c具体日期至时间

c具体日期至时间,c,date,seconds,time-t,C,Date,Seconds,Time T,我想用C将特定日期转换为秒。例如,如果我给出2015年12月25日,它将转换为秒。 这是我找到的将当前日期转换为秒的程序。但我想从特定日期转换为秒 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);

我想用C将特定日期转换为秒。例如,如果我给出2015年12月25日,它将转换为秒。 这是我找到的将当前日期转换为秒的程序。但我想从特定日期转换为秒

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); 
的结果是自UTC 1970-01-01 00:00:00午夜以来的秒数(给出或获取几闰秒)


这也称为。

阅读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,可能无法得到想要的结果。

您可能还发现strtime(3)很有用

#包括
#包括
#包括
int
main(int ac,char*av[])
{
字符格式[]=%m/%d/%y;
字符输入[]=“12/25/15”;
char-buf[256];
struct-tm;
memset(&tm,0,sizeof tm);
if(strtime(输入、格式和tm)==NULL){
fputs(“strtime失败\n”,stderr);
返回1;
}
strftime(buf,sizeof(buf),%d%b%Y%H:%M,&tm);
printf(“重新格式化:%s;按时间:%ld\n”,buf,mktime(&tm));
返回0;
}

C++还是C?您的代码似乎是C,而不是C++我不知道如何轻松获得比Unix Time提供的更精确的值。
%f
或“
%lf
”在
printf()
中的含义完全相同,因为C99(它们在
scanf()
中有所不同)。
#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;
}