【C/C++时间系列】字符串通过strptime函数转换成struct tm

字符串可以通过strptime函数转换成分解的时间struct tm。关于struct tm的介绍可看 【C/C++时间系列】struct tm 通过strftime转换成字符串 。

【strptime】

strptime主要用于把字符串转换成分解时间,与strftime的作用相反。都位于time.h中,其原始模型如下

/* Parse S according to FORMAT and store binary time information in TP.
   The return value is a pointer to the first unparsed character in S.  */
extern char *strptime (__const char *__restrict __s,
                       __const char *__restrict __fmt, 
					 struct tm *__tp);

函数的返回值是个指针,共3个参数。主要用法如下

第一个参数输入一个char*的指针,由于是用c++ 的string实现的,通过c_str()进行兼容

string mystr="2018-07-27 23:50"

mystr.c_str()

第二个参数统一是char*的指针,是用于格式控制的字符串的指针,同样用c_str()兼容

string myformat="%Y-%m-%d %H:%M"
myformat.c_str()

第三个参数 主要用于分解时间的存储,即strptime的处理结果。其类型是 struct tm 类型的指针。可以先定义一个 struct tm 类型的数据,然后通过 & 符号实现

struct tm mytm
&mytm

上述过程即实现  给strptime 传入 mystr.c_str() ,myformat.c_str()  和&mytm 三个参数,通过mystr 与myformat中对应的格式,把对应的数据存入 mytm的各个成员中,实现字符串转换成分解时间。

完整的代码实现如下

#include <iostream>
#include <string>
#include <time.h>
using namespace std;

int main()
{
    string mystr="2018-07-27 23:50";
    string myformat="%Y-%m-%d %H:%M";
    struct tm mytm;

    cout<<"mystr    is:"<<mystr<<endl;
    cout<<"myformat is:"<<myformat<<endl;

    strptime(mystr.c_str(),myformat.c_str(),&mytm);

    cout<<"print mytm:"<<endl;
 // cout<<"tm_sec:"<<mytm.tm_sec<<endl;
    cout<<"tm_min:"<<mytm.tm_min<<endl;
    cout<<"tm_hour:"<<mytm.tm_hour<<endl;
    cout<<"tm_mday:"<<mytm.tm_mday<<endl;
    cout<<"tm_mon:"<<mytm.tm_mon<<endl;
    cout<<"tm_year:"<<mytm.tm_year<<endl;

}

编译执行如下

$
$gcc -lstdc++ l_strptime.cpp -o l_strptime
$./l_strptime 
mystr    is:2018-07-27 23:50
myformat is:%Y-%m-%d %H:%M
print mytm:
tm_min:50
tm_hour:23
tm_mday:27
tm_mon:6
tm_year:118
$

其中有三点需要注意下

1、tm_mon显示月份的时候是6,代码中的是 07,即struct tm中 tm_mon 从0 开始的

2、tm_year 是118,即struct tm中tm_year是用现在的时间减去1900,得到的,即2018-1900=118

3、源码中 tm_sec是注释掉的。因为mystr与myformat中没有对应的s的数据。可以去掉注释 实现观察下。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值