日期时间函数(1)-time()&gmtime()&strftime()&localtime()
◆time()
取得当前时间。此函数会返回从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数。如果参数t为非空指针的话, 此函数也会将返回值存到t指针所指的内存。
成功则返回秒数, 失败则返回((time_t)-1)值, 错误原因存于errno中。
#include <time.h> time_t time(time_t *t);
例:
#include <time.h> #include <stdio.h> int main() { int seconds = time((time_t *)NULL); printf("%d\n", seconds); return 0; }
运行结果:1517968358
◆gmtime()
返回当时时间,不过该函数返回的时间日期未经时区转换, 而是UTC时间
#include <time.h> struct tm *gmtime(const time_t *timep);
例:
#include <time.h> #include <stdio.h> int 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 \n", (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); return 0; }
运行结果:
2018/2/7
Wed 1:55:53
◆localtime()
取得当地目前的时间和日期。与gmtime()函数不同的是,该函数返回的时间日期已经转换成当地时区。
#include <time.h> struct tm *localtime(const time_t *timep);
例:
#include <stdio.h> #include <time.h> int main() { char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};\ time_t timep; struct tm *p; time(&timep); // Get local time p = localtime(&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); return 0; }
运行结果:
2018/2/7 Wed 10:0:32
◆strftime()
格式化日期时间。该函数会把结构体tm根据format所指定的字符串格式做转换,并将转换后的内容复制到参数s所指的字符串数组中。
#include <time.h> size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
例:
#include <time.h> #include <stdio.h> int main() { char *format[] = {"%I, %M, %S, %p, %m/%d %a", "%x %X %Y", NULL}; char buf[30]; int i; time_t clock; struct tm *tm; time(&clock); tm = gmtime(&clock); for (i = 0; format[i] != NULL; i++) { strftime(buf, sizeof(buf), format[i], tm); printf("%s=> %s\n", format[i], buf); } return 0; }
运行结果:
%I, %M, %S, %p, %m/%d %a=> 02, 04, 53, AM, 02/07 Wed
%x %X %Y=> 02/07/18 02:04:53 2018
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2017-02-07 C语言基础(16)-指针
2017-02-07 C语言基础(15)-多文件编译