【问题标题】:Why I got 1 hour wrong when converting time string to tm with strptime? [closed]为什么我在使用 strptime 将时间字符串转换为 tm 时出错了 1 小时? [关闭]
【发布时间】:2022-09-22 22:36:39
【问题描述】:

我正在使用 strptime() 将时间字符串转换为 *tm

这是我的代码

string ts(\"2023-12-30 22:50:50\");

struct tm ti;

strptime(ts, \"%F %T\", &ti);

std::cout << \"time string: \" << ts << endl
          << \"ti: \" << (ti.tm_year+1900) << \"-\" << (ti.tm_mon+1) << \"-\" << ti.tm_mday << \" \" << ti.tm_hour << \":\" << ti.tm_min << \":\" << ti.tm_sec << endl;

这是我得到的

time string: 2023-12-30 22:50:50
ti: 2023-12-30 21:50:50

有关更多信息:我的时区应该是 -0600(美国中心时间),但是当我使用 \"date \'+%Y-%m-%d %H:%M:%S %z\ 显示时,它会显示 -0500 ”。我认为这是由夏令时引起的。我错了吗?但是 2023-12-30 不是夏令时。

  • 什么时区?无论如何,请提供minimal reproducible example
  • 我收到error: cannot convert \'std::string\' {aka \'std::__cxx11::basic_string&lt;char&gt;\'} to \'const char*\'。你能发一个minimal reproducible example吗?
  • 对不起这是我的错。我的原始代码是 strptime(ts.c_str(), \"%F %T\", &amp;ti); 我在输入时忘记了 .c_str()。

标签: c++ time


【解决方案1】:

我把strptime的第一个参数改成了tm.c_str()。以下是所有代码供您参考。

#include <time.h>
#include <iostream>
using namespace std;
int main() {
    string str_time("2023-12-30 22:50:50");
    struct tm ti;
    strptime(str_time.c_str(), "%F %T", &ti);
    std::cout << "time string: " << str_time << endl
            << "ti: " << (ti.tm_year+1900) << "-" << (ti.tm_mon+1) << "-" << ti.tm_mday << " " << ti.tm_hour << ":" << ti.tm_min << ":" << ti.tm_sec << endl;
    return 0;
}

使用 g++ 9.4.0 构建

gxie@ubuntu:~/test $ g++ test.cpp
gxie@ubuntu:~/test $ ./a.out
time string: 2023-12-30 22:50:50
ti: 2023-12-30 22:50:50

【讨论】:

    猜你喜欢
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    相关资源
    最近更新 更多