博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
日期时间函数(1)-time()&gmtime()&strftime()&localtime()
阅读量:7222 次
发布时间:2019-06-29

本文共 2169 字,大约阅读时间需要 7 分钟。

◆time()

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

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

#include 
time_t time(time_t *t);

例:

#include 
#include
int main(){ int seconds = time((time_t *)NULL); printf("%d\n", seconds); return 0;}

运行结果:1517968358

◆gmtime()

返回当时时间,不过该函数返回的时间日期未经时区转换, 而是UTC时间

#include 
struct tm *gmtime(const time_t *timep);

例:

#include 
#include
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 
struct tm *localtime(const time_t *timep);

例:

#include 
#include
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 
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);

例:

#include 
#include
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

 

转载地址:http://zbkfm.baihongyu.com/

你可能感兴趣的文章
19-04-25
查看>>
一个JAVA程序员成长之路分享
查看>>
30K iOS程序员的简述:如何快速进阶成为高级开发人员
查看>>
Go 夜读 - 每周四晚上 Go 源码阅读技术分享
查看>>
tranform知多少
查看>>
Android电量优化
查看>>
[爬虫手记] 我是如何在3分钟内开发完一个爬虫的
查看>>
【译】Css Grid VS Flexbox: 实践比较
查看>>
iOS 开发知识索引
查看>>
Linux iptables命令
查看>>
webpack的使用
查看>>
干货 | 基于Go SDK操作京东云对象存储OSS的入门指南
查看>>
D3.js入门
查看>>
一次和前端的相互甩锅的问题记录
查看>>
纯OC实现iOS DLNA投屏功能了解一下
查看>>
RxJava -- fromArray 和 Just 以及 interval
查看>>
LC #75 JS
查看>>
js正则验证代码库
查看>>
常见面试题—css实现垂直水平居中
查看>>
lc682. Baseball Game
查看>>