1. localtime()函数
localtime用来获取系统时间,精度为秒
函数原型
struct tm *localtime(const time_t * timep)
头文件
#include <time.h>
示例:
#include <stdio.h> #include <sys/time.h> #include <time.h> #include <unistd.h> int main() { while (1) { time_t t = time(NULL); struct tm *tm = localtime(&t); printf("localtime:%02d/%02d/%02d-%02d:%02d:%02d\n", tm->tm_mon + 1, tm->tm_mday, tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); sleep(1); } return 0; }
运行结果
localtime:10/04/2013-01:11:33 localtime:10/04/2013-01:11:34 localtime:10/04/2013-01:11:35 localtime:10/03/2013-23:11:36 localtime:10/03/2013-23:11:37 localtime:10/03/2013-23:11:38
2. localtime_r()函数
用来获取系统时间,运行于linux平台下
函数原型
struct tm *localtime_r(const time_t *timep, struct tm *result);
示例:
#include <stdio.h> #include <sys/time.h> #include <time.h> #include <unistd.h> int main() { while (1) { time_t t = time(NULL); struct tm local_tm; struct tm *tm = localtime_r(&t, &local_tm); printf("localtime_r:%02d/%02d/%02d-%02d:%02d:%02d\n", tm->tm_mon + 1, tm->tm_mday, tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); sleep(1); } return 0; }
运行结果
localtime_r:10/04/2013-01:15:37 localtime_r:10/04/2013-01:15:38 localtime_r:10/04/2013-01:15:39 localtime_r:10/04/2013-01:15:40 localtime_r:10/04/2013-01:15:41 localtime_r:10/04/2013-01:15:42
3. localtime_s()函数
用来获取系统时间,运行于windows平台下,与localtime_r只有参数顺序不一样
#include <iostream>
#include <time.h>
int main()
{
time_t time_seconds = time(0);
struct tm now_time;
localtime_s(&now_time,&time_seconds);
printf("%d-%d-%d %d:%d:%d\n", now_time.tm_year + 1900, now_time.tm_mon + 1,
now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec);
}