C语言中读取时间日期的基本方法

2025-05-27 0 42

C语言time()函数:获取当前时间(以秒数表示)
头文件:

?

1
#include <time.h>

定义函数:

?

1
time_t time(time_t *t);

函数说明:此函数会返回从公元 1970 年1 月1 日的UTC 时间从0 时0 分0 秒算起到现在所经过的秒数。如果t 并非空指针的话,此函数也会将返回值存到t 指针所指的内存。

返回值:成功则返回秒数,失败则返回((time_t)-1)值,错误原因存于errno 中。

范例

?

1

2

3

4

5
#include <time.h>

main(){

int seconds = time((time_t*)NULL);

printf("%d\\n", seconds);

}

执行结果:

?

1
9.73E+08

C语言gmtime()函数:获取当前时间和日期
头文件:

?

1
#include <time.h>

定义函数:

?

1
struct tm *gmtime(const time_t *timep);

函数说明:gmtime()将参数timep 所指的time_t 结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果由结构tm 返回。

结构tm 的定义为

?

1

2

3

4

5

6

7

8

9

10

11
struct tm{

int tm_sec; //代表目前秒数, 正常范围为0-59, 但允许至61 秒

int tm_min; //代表目前分数, 范围0-59

int tm_hour; //从午夜算起的时数, 范围为0-23

int tm_mday; //目前月份的日数, 范围01-31

int tm_mon; //代表目前月份, 从一月算起, 范围从0-11

int tm_year; //从1900 年算起至今的年数

int tm_wday; //一星期的日数, 从星期一算起, 范围为0-6

int tm_yday; //从今年1 月1 日算起至今的天数, 范围为0-365

int tm_isdst; //日光节约时间的旗标

};

此函数返回的时间日期未经时区转换,而是UTC 时间

返回值:返回结构tm 代表目前UTC 时间

范例

?

1

2

3

4

5

6

7

8

9

10
#include <time.h>

main(){

char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

time_t timep;

struct tm *p;

time(&timep);

p = gmtime(&timep);

printf("%d%d%d", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday);

printf("%s%d;%d;%d\\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);

}

执行结果:

?

1
2000/10/28 Sat 8:15:38

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C语言中读取时间日期的基本方法 https://www.kuaiidc.com/75535.html

相关文章

发表评论
暂无评论