例如,我可以通过查看这两个日期来计算它们的差值,但我不知道如何在程序中进行计算。
日期:A为2014/02/12(y/m/d) 13:26:33,B为2014/02/14(y/m/d) 11:35:06,则小时差为46。
发布于 2014-02-19 04:32:05
我假设你的商店时间是字符串:"2014/02/12 13:26:33"
要计算时间差,您需要使用:double difftime( time_t time_end, time_t time_beg);
函数difftime()作为time_t对象(time_end - time_beg)以秒为单位计算两个日历时间之间的差值。如果time_end指的是time_beg之前的时间点,则结果为负。现在的问题是difftime()不接受字符串。我们可以通过两个步骤将字符串转换为在time.h中定义的time_t结构,正如我在我的回答中所描述的:How to compare two time stamp in format “Month Date hh:mm:ss”:
strptime()函数使用format指定的格式将buf指向的字符串转换为存储在tm指向的tm结构中的值。要使用它,您必须使用文档中指定的格式字符串:
对于您的时间格式,我将解释格式字符串:
1. %Y: 4-digit year. Can be negative.
2. %m: Month [1-12]
3. %d: Day of the month [1–31]
4. %T: 24 hour time format with seconds, same as %H:%M:%S (you can also use %H:%M:%S explicitly)所以函数调用如下所示:
// Y M D H M M S strptime("2014/02/12 13:26:33",“%Y/%m/%d%T”,&tmi)
其中tmi是struct tm结构。
time_t mktime(struct tm *time);下面是我写的代码(阅读评论):
#define _GNU_SOURCE //to remove warning: implicit declaration of ‘strptime’
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void){
char* time1 = "2014/02/12 13:26:33"; // end
char* time2 = "2014/02/14 11:35:06"; // beg
struct tm tm1, tm2; // intermediate datastructes
time_t t1, t2; // used in difftime
//(1) convert `String to tm`: (note: %T same as %H:%M:%S)
if(strptime(time1, "%Y/%m/%d %T", &tm1) == NULL)
printf("\nstrptime failed-1\n");
if(strptime(time2, "%Y/%m/%d %T", &tm2) == NULL)
printf("\nstrptime failed-2\n");
//(2) convert `tm to time_t`:
t1 = mktime(&tm1);
t2 = mktime(&tm2);
//(3) Convert Seconds into hours
double hours = difftime(t2, t1)/60/60;
printf("%lf\n", hours);
// printf("%d\n", (int)hours); // to display 46
return EXIT_SUCCESS;
}编译并运行:
$ gcc -Wall time_diff.c
$ ./a.out
46.142500发布于 2014-02-19 02:58:14
您可以在C中使用difftime()来计算两次之间的差值。但是,它使用mktime和tm。
double difftime(time_t time1, time_t time0);发布于 2014-02-19 03:01:06
一种简单的方法(不讨论时区)是将两个日期(日期时间)转换为自1970年1月1日以来的秒数。构建差与(tada)之差为3600
如果我没记错的话,mktime()应该可以完成这项工作
HTH
https://stackoverflow.com/questions/21862808
复制相似问题