linux c时间编程

2019-07-12 23:56发布

嵌入式linux c时间编程

时间类型

Calendar Time 日历时间
从一个标准时间(1900年1月1日0点)到此时经过的秒数。
UTC/GMT
UTC(Coordinated Universal Time)世界标准时间 即 GMT(Greenwich Mean Time)格林威治标准时间。

常用时间函数

(1) time
time_t time(time_t *tloc); 获取日历时间。 (2) struct tm *localtime(const time_t *timep); 获取日历事件转换后的本地时间,结构体包含以下成员: struct tm
{
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
}; (3) char *asctime(const struct tm *tm); 将本地时间以字符串形式打印。
(4)time_t mktime(struct tm *tm); 将本地时间转换为日历时间。

代码用例

(1)时间函数综合用例 #include #include #include #include int main(int argc, char *argv[]) { time_t curTime = 0; struct tm *localTime = NULL; time_t timeValue = 0; curTime = time((time_t*)NULL); localTime = localtime(&curTime); timeValue = mktime(localTime); printf("Current time is:%s curTime:%lu, timeValue:%lu ", asctime(localTime), curTime, timeValue); return 0; } 这里写图片描述
(2)结合项目的时间函数使用。
项目要求,设备开机后,如果当前时间(hour:minute:seconds)大于设定红外led开启时间,则打开led的灯,此处要进行时间的对比。可以修改当前时间的 hour:minute:seconds数值位设定值,获取nightModeOnTime,然后与当前时间进行比较。代码如下: void getNightModeTime(struct tm *localTime, LightMode_E lightMode) { if (lightMode == LightMode_Night) { localTime->tm_hour = g_imgDisAttr.nightModeOnTime.hour; localTime->tm_min = g_imgDisAttr.nightModeOnTime.minute; localTime->tm_sec = g_imgDisAttr.nightModeOnTime.seconds; } else if (lightMode == LightMode_Day) { localTime->tm_hour = g_imgDisAttr.nightModeOffTime.hour; localTime->tm_min = g_imgDisAttr.nightModeOffTime.minute; localTime->tm_sec = g_imgDisAttr.nightModeOffTime.seconds; } else { return; } return; } /* 获取当前时间 */ curTime = time((time_t *)NULL); localTime = localtime(&curTime); memcpy (&tmpLocalTime, localTime, sizeof(struct tm)); /* 获取夜间模式开启时间 */ getNightModeTime(&tmpLocalTime, LightMode_Night); nightModeOnTime = mktime(&tmpLocalTime); /* 获取夜间模式关闭时间 */ getNightModeTime(&tmpLocalTime, LightMode_Day); nightModeOffTime = mktime(&tmpLocalTime); /* ontime:18:00 offtime:08:00 场景 */ if (nightModeOnTime >= nightModeOffTime) { if (curTime >= nightModeOnTime || curTime <= nightModeOffTime) { cmiotSetSceneIR(NightSwitch_TIME); } else { cmiotSetSceneNormal(NightSwitch_TIME); } }