我试图使用getDateTime计算两个不同时间日期之间的差异:假设如下所示:
输入日期和时间(yyyy-mm-dd hh:mm:ss): 2017-03-13 12:00:00 Start: Mon Mar 13 12:00:00 2017
输入日期和时间(yyyy-mm-dd hh:mm:ss): 2017-03-13 12:00:30 End: Mon Mar 13 12:00:30 2017
差:30秒。
这是我的尝试:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int dayOfWeek(int d, int m, int y){
// Compute day of week: 0 Sun 1 Mon...6 Sat
int z;
if(m<3){
z=y;
y=y-1;
}
else z=y-2;
return (23*m/9 + d + z + 4 +
y/4- y/100 + y/400)%7;
}
int getDateTime(struct tm *t){
int year,month,day,hrs,min,sec;
printf("Enter date and time (yyyy-mm-dd hh:mm:ss): ");
scanf("%d-%d-%d", &year, &month, &day);
scanf("%d:%d:%d",&hrs,&min,&sec);
int x;
t->tm_year = year - 1900;
t->tm_mon = month - 1;
t->tm_mday = day;
t->tm_hour = hrs;
t->tm_min = min;
t->tm_sec = sec;
t->tm_wday = dayOfWeek(day,month,year);
return ;
}
int main()
{
setvbuf(stdout, NULL, _IONBF, 0);
struct tm Time1 , Time2;
double x;
getDateTime(&Time1);
printf("Start: %s", asctime(&Time1));
getDateTime(&Time2);
printf("End: %s", asctime(&Time2));
return EXIT_SUCCESS;
}我能够以正确的格式打印它,但是如何以秒为单位计算差异呢?我试着使用不同的时间,但我认为我用错了。非常感谢!
发布于 2017-03-21 06:27:33
已经有一个函数可以解析日期,即strptime。就像约会一样。它遵循与绞合时间相同的格式代码(p表示解析,f表示格式)。
你可以用很长的手。
struct tm date;
strptime( "2017-03-13 12:00:00", "%Y-%m-%s %H:%M:%S", &date );或使用为ISO 8601日期和时间提供的短手。
struct tm date;
strptime( "2017-03-13 12:00:00", "%F %T", &date );它取代了getDateTime。
完成后,您可以将日期转换为struct tm,并将其转换为自时代(1970-01-01 : 00:00:00协调世界时)以来的秒数并减去。转换为秒从时代,time_t,是完成使用mktime。然后用difftime减去。
time_t seconds1 = mktime(&date1);
time_t seconds2 = mktime(&date2);
double timediff = difftime( seconds1, seconds2 );不过,老实说,您也可以只使用seconds1 - seconds2。difftime被添加到标准中,以允许time_t不是一个简单的数字,但我不知道这方面的实例。
mktime假定日期位于本地时区。对于在同一时区内区分两个日期的目的来说,这并不重要。
如果是这样的话,就会有非标准函数timegm,即mktime,但它假设它们是UTC日期。或者您可以使用POSIX函数setenv和tzset临时更改时区。
time_t my_timegm(struct tm *date) {
// Store the current TZ value.
char *tz = getenv("TZ");
// Unset TZ which will cause UTC to be used.
setenv("TZ", "", 1);
tzset();
// Call mktime, now in UTC.
time_t time = mktime(date);
// Restore the TZ environment variable (or leave it unset).
if (tz)
setenv("TZ", tz, 1);
else
unsetenv("TZ");
tzset();
return time;
}https://stackoverflow.com/questions/42918686
复制相似问题