【问题标题】:How to convert a "%Y%m%d" format string into a time_t variable in C++?如何在 C++ 中将“%Y%m%d”格式字符串转换为 time_t 变量?
【发布时间】:2020-04-06 10:48:42
【问题描述】:

我正在尝试将字符串转换为 time_t 变量。这是我尝试过的代码:

#include "pch.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>

using namespace std;

time_t String_to_timet1(string endDate) {
    tm tm = { 0 };
    stringstream ss(endDate);
    ss >> get_time(&tm, "%Y-%m-%d %H:%M:%S");
    time_t epoch = mktime(&tm);

    return epoch;
}

time_t String_to_timet2(string endDate) {
    tm tm = { 0 };
    stringstream ss(endDate);
    ss >> get_time(&tm, "%Y%m%d");
    time_t epoch = mktime(&tm);

    return epoch;
}

int main()
{
    time_t time_certainTime1 = String_to_timet1("2019-01-01 00:00:00");
    cout << time_certainTime1 << endl;

    time_t time_certainTime2 = String_to_timet2("20190101");
    cout << time_certainTime2 << endl;

    return 0;
}

我预计结果会是一样的,但是当我用 Visual Studio 2017 运行代码时,结果是:

1546268400
-1

当我在https://www.onlinegdb.com/online_c++_compiler 上运行相同的代码时,结果是:

1546300800
1546300800

问题:为什么 Visual Studio 在获得“%Y%m%d”类型的字符串时给我 -1(当在线编译器给我预期的结果时)?如何制作具有这种格式的 time_t 变量?

【问题讨论】:

  • 如果tm 不能表示为time_tmktime() 返回 -1。您没有进行任何错误检查以确保 std::get_time() 成功
  • 无关:C++20 有一些新工具来处理这个问题。如果你等不及了,这里是Howard Hinnant's "Prototype" of the coming additions

标签: c++ ctime time-t


【解决方案1】:

在 %m 和 %d 的文档中,它说允许使用前导零,但不是必需的。这意味着它实际上是否可以在没有分隔符的情况下工作。

【讨论】:

    猜你喜欢
    • 2021-03-09
    • 1970-01-01
    • 2021-12-22
    • 2016-09-15
    • 2018-08-12
    • 2012-07-21
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多