c语言获取系统当前时间
在C语言中,ctime 和 localtime 是两个与日期和时间处理相关的函数,但它们的用途和功能有所不同。这两个函数通常与
ctime:
char *ctime(const time_t *timer);
这个函数将一个以秒为单位的时间戳(time_t 类型)转换为一个可读的字符串形式,格式为 "Day Mon DD HH:MM:SS YYYY\n"。例如,"Wed Jun 30 21:49:08 2023\n"。
这个字符串是静态分配的,所以每次调用 ctime 时,它都会覆盖前一次的结果。
通常,你会首先使用 time(&rawtime) 来获取当前时间的时间戳,然后将其传递给 ctime 以获取可读的字符串表示。
localtime:
struct tm *localtime(const time_t *timer);
这个函数也将一个时间戳(time_t 类型)作为输入,但它返回一个指向 struct tm 结构体的指针,该结构体包含了关于时间的详细信息,如年、月、日、小时、分钟、秒等。
这个 struct tm 结构体不是静态分配的,所以你需要确保正确地管理其生命周期(例如,如果你是在函数中分配它,你可能需要在函数返回之前释放它)。
localtime 函数返回的 struct tm 结构体中的时间是基于本地时区的。
示例1
/*******************************************************************
*
* file name: get_time.c
* author : m17872844806@163.com
* date : 2024/05/31
* function : 利用time库的localtime函数获取系统当前时间
* note : None
*
* CopyRight (c) 2023-2024 m17872844806@163.com All Right Reseverd
*
* *****************************************************************/
#include
#include
int main() {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
printf("当前本地时间和日期是: %04d-%02d-%02d %02d:%02d:%02d\n",
timeinfo->tm_year + 1900, // 年份是从1900年开始的,所以要+1900
timeinfo->tm_mon + 1, // 月份是从0开始的,所以要+1
timeinfo->tm_mday,
timeinfo->tm_hour,
timeinfo->tm_min,
timeinfo->tm_sec);
return 0;
}
示例2
/*******************************************************************
*
* file name: get_time.c
* author : m17872844806@163.com
* date : 2024/05/31
* function : 利用time库的ctime函数获取系统当前时间
* note : None
*
* CopyRight (c) 2023-2024 m17872844806@163.com All Right Reseverd
*
* *****************************************************************/
#include
#include
int main() {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
printf("ctime: %s", ctime(&rawtime));
return 0;
}
如果代码用法有什么问题,请将问题发至网易邮箱 m17872844806@163.com,作者将及时改正,欢迎与各位老爷交流讨论。
麻烦三连加关注!!!!
比心