C++ Converting a time string to seconds from the epoch(C++ 将时间字符串从纪元转换为秒)
问题描述
我有一个格式如下的字符串:
I have a string with the following format:
2010-11-04T23:23:01Z
2010-11-04T23:23:01Z
Z 表示时间是 UTC.
我宁愿将其存储为纪元时间,以便于比较.
The Z indicates that the time is UTC.
I would rather store this as a epoch time to make comparison easy.
推荐的方法是什么?
目前(经过快速搜索)最简单的算法是:
Currently (after a quck search) the simplist algorithm is:
1: <Convert string to struct_tm: by manually parsing string>
2: Use mktime() to convert struct_tm to epoch time.
// Problem here is that mktime uses local time not UTC time.
推荐答案
使用 C++11 功能,我们现在可以使用流来解析时间:
Using C++11 functionality we can now use streams to parse times:
iomanip std::get_time
将根据一组格式参数转换一个字符串,并将它们转换为 struct tz
对象.
The iomanip std::get_time
will convert a string based on a set of format parameters and convert them into a struct tz
object.
然后您可以使用 std::mktime()
将其转换为纪元值.
You can then use std::mktime()
to convert this into an epoch value.
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
int main()
{
std::tm t = {};
std::istringstream ss("2010-11-04T23:23:01Z");
if (ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S"))
{
std::cout << std::put_time(&t, "%c") << "
"
<< std::mktime(&t) << "
";
}
else
{
std::cout << "Parse failed
";
}
return 0;
}
这篇关于C++ 将时间字符串从纪元转换为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 将时间字符串从纪元转换为秒


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01