c++ - 尝试将存储在 char 中的时间转换为正常形式。打印一个随机值。怎么了?

标签 c++ time

这是我编写的一段简短代码,用于将以字符串或字符形式输入的时间打印为 hh:mm:ss 格式。 没有编译错误,但给出了垃圾值。它出什么问题了? 注意:我不想打印日/月/年。

# include<iostream>
# include<ctime>
using namespace std;

int main(){

        const char *time_details = "15:34:12";
        struct tm tm;
        strptime(time_details, "%H:%M:%S", &tm);
        time_t t = mktime(&tm);
        cout << t  << endl;


}

最佳答案

来自 strptime 的手册页:

If the format string does not contain enough conversion specifications to completely specify the resulting struct tm, the unspecified members of tm are left untouched.

您需要设置那些其他成员,或者只使用您设置的成员。

更新
这里的另一个问题是 mktime 的使用。从该函数的 OpenGroup 描述中,

If the time since the Epoch cannot be represented, the function shall return the value (time_t)-1

如果您简单地将结构 tm 置零,您将创建一个无法用 Unix 时间格式表示的时间(自 00Z,1970 年 1 月 1 日以来的秒数)。至少,您需要将年和月中的日期设置为非零值。

关于c++ - 尝试将存储在 char 中的时间转换为正常形式。打印一个随机值。怎么了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11295460/

相关文章:

Mysql最近一小时数据

c++ - C/C++ 衡量程序效率

c++ - 如何从 LLVM 中的终止符指令中删除后继指令

c++ - 我在识别浮点异常时遇到问题

c++ - ns3中udp连接的吞吐量计算

JavaScript Date() 行为异常,知道哪里出了问题吗?

java - 日期时间字符串 + TimeZone

python - (Euler 项目 #3)试图将 Python 中的解决方案复制到 C++ 中,但出现了可怕的错误,不知道怎么做

ruby-on-rails - 在 Rails 中表达 "less than an hour in the future"的最佳方式?

python - 如何使用 matplotlib 按时绘制事件