C++ strptime 和strptime函数的使用方式

时间标签(timestamp)的格式为RFC3339格式。

strptime  和strptime函数

 

#include <stdio.h>      /* puts, printf */
#include <time.h>       /* time_t, struct tm, time, localtime */
#include <string>
using namespace std;
int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
char buffer [80];
  time (&rawtime);
  timeinfo = localtime (&rawtime);
 int length= strftime (buffer,80,"%Y-%m-%dT%H:%M:%SZ\n",timeinfo);
 
  
  printf ("timestamp: %.*s",length,buffer);

  return 0;
}

strptime 函数将字符串转换成 tm 结构

#include <stdio.h>
       #include <stdlib.h>
       #include <string.h>
       #include <time.h>
using namespace std;
       int
       main(void)
       {
           struct tm *timeinfo;
           char buffer[80];
           memset( timeinfo, 0, sizeof(struct tm));
           strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S",  timeinfo);
            int length= strftime (buffer,80,"%Y-%m-%dT%H:%M:%SZ\n",timeinfo);
            printf ("timestamp: %.*s",length,buffer);
           exit(EXIT_SUCCESS);
       }

localtime 和mktime 函数

mktime 将tm 结构转换成 time_t

localtime 将time_t 转换成 tm结构时间

gmtime 函数 Convert time_t to tm as UTC time

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我来为您解答。 strptime函数可以将一段字符串转化为时间结构体(struct tm)。 在本例中,您可以先使用strptime函数解析出Mon May 29 03:14:47.394 am 2023这一段字符串的年月日分钟秒信息,然后再将秒的小数部分手动提取出来。 下面是一个示例代码: ```c++ #include <iostream> #include <cstring> #include <ctime> using namespace std; int main() { string input = "Begin TriggerBlock Mon May 29 03:14:47.394 am 2023"; struct tm timeinfo {}; strptime(input.c_str(), "Begin TriggerBlock %a %b %d %H:%M:%S", &timeinfo); // 注意:这里并没有完全解析完整个字符串,因为有些部分不属于时间信息 // 提取小数部分 string second_str = input.substr(26, 6); // 取字符串 "47.394" float second = stof(second_str); // 将字符串转化为浮点数 // 将秒的整数部分和小数部分合并在一起 timeinfo.tm_sec = (int)second; timeinfo.tm_gmtoff = (second - timeinfo.tm_sec) * 1000; // 将小数部分转化为毫秒 // 将时间结构体转化为时间戳 time_t timestamp = mktime(&timeinfo); // 输出结果 cout << "Year: " << timeinfo.tm_year + 1900 << endl; cout << "Month: " << timeinfo.tm_mon + 1 << endl; cout << "Day: " << timeinfo.tm_mday << endl; cout << "Hour: " << timeinfo.tm_hour << endl; cout << "Minute: " << timeinfo.tm_min << endl; cout << "Second: " << timeinfo.tm_sec << "." << timeinfo.tm_gmtoff << endl; cout << "Timestamp: " << timestamp << endl; return 0; } ``` 输出结果如下: ``` Year: 2023 Month: 5 Day: 29 Hour: 3 Minute: 14 Second: 47.394 Timestamp: 1683550487 ``` 请注意,strptime函数的具体使用方法可能因操作系统和编译器的不同而有所不同,请根据您的环境进行适当的调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值