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

2023-06-30C/C++开发问题
40

本文介绍了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++ 将时间字符串从纪元转换为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6