【C语言】日期时间转秒数

日期时间转秒数

将例如“2020年8月14日 12:30:15”的日期时间转换为从1970年1月1日0时0分0秒开始至今的UTC时间秒数,不计闰秒。(中国大陆、中国香港、中国澳门、中国台湾与UTC的时差为+8)。

示例

#include 
#include 
#include 

time_t datetime2sec(int year, int mon, int day, int hour, int min, int sec)
{
    struct tm tt;
    memset(&tt, 0, sizeof(tt));
    tt.tm_year = year - 1900;
    tt.tm_mon = mon - 1;
    tt.tm_mday = day;
    tt.tm_hour = hour;
    tt.tm_min = min;
    tt.tm_sec = sec;
    return mktime(&tt);
}

int main()
{
	printf("%lld\n", datetime2sec(1970, 1, 1, 8, 0, 0)); 
    printf("%lld\n", datetime2sec(2020, 8, 14, 12, 30, 15));
    return 0;
}
/*output
0
1597379415
*/

time_t类型

#include 
typedef /* unspecified */ time_t;

虽然C标准没有规定,但是建议使用long long类型来存储time_t类型的值,以确保暂时不溢出。

tm结构

#include 
struct tm{
	int tm_sec;		// 秒 [0, 60] (C99之前的范围是[0, 61])
	int tm_min;		// 分 [0, 59]
	int tm_hour;	// 小时 [0, 23]
	int tm_mday;	// 日 [1, 31]
	int tm_mon;		// 月 [0, 11]
	int tm_year;	// 年 [1900, ~]
	int tm_wday;	// 星期几 [0, 6] 从星期日开始
	int tm_yday;	// 天数 [0, 365]
	int tm_isdst;	// 夏时令,若有效为正值,无效为0,无可用信息为负值
};

tm结构中变量的范围虽然有规定,但是超出范围时也有效,比如:

  • datetime2sec(1970, 1, 1, 8, 0, 999); // 999
  • datetime2sec(2020, 7, 45, 12, 30, 15); // 1597379415

mktime函数

#include 
time_t mktime( struct tm *time );

成功返回从纪元开始计算的秒数,失败则返回 -1(即time_t溢出)。

技巧

如何计算2008年2月的最后一秒

2008年2月有多少天呢?并不需要知道。

  • datetime2sec(2008, 3, 1, 0, 0, 0) - 1;

你可能感兴趣的:(温故知新)