C++ 将时间字符串从纪元转换为秒

2021-12-23 00:00:00 time c c++ platform-independent

我有一个格式如下的字符串:

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;
}

相关文章