时间操作 - 时间格式转换

说明

  • 编程中,时间格式转换是常用的功能,特别是与格式化字符串之间的互相转换。

时间转格式化字符串

  1. 固定格式字符串 - asctime/asctime_r/ctime/ctime_r函数
  • asctime/asctime_r函数支持将一个struct tm结构格式化为一个固定格式字符串;ctime/ctime_r函数支持将一个time_t变量转换为一个固定格式字符串。
  • 固定格式:Www Mmm dd hh:mm:ss yyyy,Www 表示星期几,Mmm 是以字母表示的月份,dd 表示一月中的第几天,hh:mm:ss 表示时间,yyyy 表示年份
* 函数原型如下:
#include <time.h>

char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);
char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);

* 示例
time_t curtime;
time(&curtime);
struct tm t;
gmtime_r(&curtime, &t);

puts(asctime(&t)
printf("当前时间 = %s", ctime(&curtime));

* 函数说明
asctime和ctime采用静态变量保存的转换结果,不是线程安全的,asctime_r和ctime_r是其线程安全版本
  1. 自定义格式字符串 - strftime函数
  • 函数支持将一个struct tm结构格式化为一个自定义格式的字符串。
* 函数原型如下:
#include <time.h>

size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);

* 参数说明
s     : 转换结果输出buf 
max   :输出buf(s)的内存空间大小
format:转换后字符串的格式
tm    :输入,struct tm结构的时间

* format格式控制符号
%a : 星期几的简写形式
%A : 星期几的全称
%b : 月份的简写形式
%B : 月份的全称
%c : 日期和时间
...
更多格式请看man中的帮助说明

* 示例:
char time_str[20] = {0};
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M", localtime(&now));

* 运行结果
2020-11-28 21:52
  • strftime函数可以满足大部分需求,示例:嵌入式Http服务器goahead不支持新的RFC1123标准的时间字符串,需要自主实现,如下:
RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z"; //新式RFC1123标准的时间字符串格式
asctimePattern = "EEE MMM d HH:mm:ss yyyyy"; //当前goahead采用的时间字符串格式
* 使用strftime实现新标准
char buf[100] = {0};
strftime(buf,100,"%a, %d %b %Y %H:%M:%S %Z", &tm); 
  1. 自定义格式字符串 - 自主实现
  • 可通过sprintf函数实现自定义格式化。

格式化字符串转时间

  1. 自定义格式字符串 - strptime函数
  • 函数支持将一个格式化字符串转换为一个struct tm结构,函数原型如下:
* 函数原型如下:
#include <time.h>

char *strptime(const char *buf,const char*format,struct tm *timeptr)

* 参数说明
buf    : 输入的格式化时间字符串
format : 输入字符串的格式(与strftime中的格式一样)
timeptr: 输出时间转换结果
返回:返回一个指针,指向转换后的剩余字符。

* 示例:
struct tm tm;   
char buf[255] = "24/Aug/2011:09:42:35";  
        
strptime(buf, "%d/%b/%Y:%H:%M:%S" , &tm); 

* 运行结果
tm中保存了转换后的时间
  1. 自定义格式字符串 - 自主实现
  • 可通过sscanf函数实现自定义格式字符串转换成时间。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值