linux c语言 时间函数 带时区转换
概念
utc 时间
世界协调时间(Universal Time Coordinated,UTC): GPS 系统中有两种时间区分,一为UTC,另一为LT(地方时)两者的区别为时区不同,UTC就是0时区的时间,地方时为本地时间,如北京为早上八点(东八区),UTC时间就为零点,时间比北京时晚八小时,以此计算即可。
也就是太阳晒到本初子午线的时候,其实已经早就在东方-中国晒了8小时了。
Linux下可以通过运行命令tzselect然后输入选项前面的数字来一步一步地设置当前系统时区。
另外一种设置可以使用配置文件来设置系统时间,参考blog说明
在linux系统中,UTC秒数一般来说,都是相对于1970年01月01日0点0分0秒的秒数
比如 0秒,表示在格林尼治(本次子午线)时间是1970-01-01 00:00:00
而0秒代表此时的中国-上海时间是 1970-01-01 08:00:00
函数
time()
time() 取得目前的时间
表头文件:#include <time.h>
定义函数:time_t time(time_t *t);
函数说明:此函数会返回从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数。如果t 并非空指针的话,此函数也会将返回值存到t指针所指的内存。
返回值:成功则返回秒数,失败则返回((time_t)-1)值,错误原因存于errno中。
————————————————
版权声明:本文为CSDN博主「ac他」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43605112/article/details/87455626
#include <stdio.h>
#include <time.h>
int main()
{
time_t t;
t = time(NULL);
printf("自1970来到现在一共过去了秒数:%d\n",t);
return 0;
}
ftime()
特点是带了时区
ftime()函数取得目前的时间和日期。
相关函数:time, ctime, gettimeofday
表头文件:#include <sys/timeb.h>
函数定义:int ftime(struct timeb *tp);
函数说明:ftime()将目前日期由tp所指的结构返回。tp结构定义:
struct timeb{
time_t time; /* 为1970-01-01至今的秒数*/
unsigned short millitm; /* 千分之一秒即毫秒 */
short timezonel; /* 为目前时区和Greenwich相差的时间,单位为分钟 */
short dstflag; /* 为日光节约时间的修正状态,如果为非0代表启用日光节约时间修正 */
};
返回值 :无论成功或失败都返回0
gettimeofday()
获取时间的秒放在timeval结构体中,可以到微妙
也能带时区
#include<sys/time.h>
int gettimeofday(struct timeval*tv,struct timezone *tz )
timevalstruct timeval{
long tv_sec;/*秒*/
long tv_usec;/*微妙*/
};
timezone 结构定义为:
struct timezone{
int tz_minuteswest;/*和greenwich 时间差了多少分钟*/
int tz_dsttime;/*type of DST correction*/
}
在gettimeofday()函数中tv或者tz都可以为空。如果为空则就不返回其对应的结构体。
函数执行成功后返回0,失败后返回-1,错误代码存于errno中。
localtime()
核心是将utc的秒,根据当地时区转换为当地时间。注意在转换的时候已经增加了时区的换算,前提是系统的时区是对的
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
time_t rawtime;
struct tm *info;
char buffer[80];
time( &rawtime );
info = localtime( &rawtime );
cout<<"current time is:" << asctime(info) << endl;
cout << "year is: " << info->tm_year+1900 << endl;
cout << "month is: " << info->tm_mon+1 << endl;
cout << "day is: " << info->tm_mday << endl;
cout << "hour is: " << info->tm_hour << endl;
cout << "min is: " << info->tm_min << endl;
}
执行结果:
current time is Fri May 8 11:17:26 2020year is: 2020
month is: 5
day is: 8
hour is: 11
min is: 17
mktime()
和localtime刚好相反,是将struct tm格式转换为UTC的秒,注意转换的过程会根据本地时区来转换到UTC的秒。
描述C 库函数
time_t mktime(struct tm *timeptr)
把 timeptr 所指向的结构转换为一个依据本地时区的 time_t 值。
声明下面是 mktime() 函数的声明。
time_t mktime(struct tm *timeptr)
struct tm {
int tm_sec; /* 秒,范围从 0 到 59 */
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; /* 夏令时 */
};
返回值该函数返回一个 time_t 值,该值对应于以参数传递的日历时间。如果发生错误,则返回 -1 值。