C++将格式化的时间转换为时间戳展开 

在C++中,可以使用<chrono><iomanip>头文件中的类和函数将格式化的时间转换为时间戳。以下是一个例子,演示如何将"年-月-日 时:分:秒"格式的时间转换为自1970年1月1日以来的秒数。

#include <iostream>

#include <sstream>

#include <iomanip>

#include <chrono>

#include <ctime>

// 将格式化的时间转换为时间戳

time_t convert_formatted_time_to_timestamp(const std::string& formatted_time) {

std::istringstream ss(formatted_time);

std::tm tm = {};

char separator;

// 解析时间

ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");

if (ss.fail()) {

// 如果解析失败,则可能是由于格式不正确导致的

return -1; // 返回错误标识

}

// 将tm结构转换为time_t

return mktime(&tm);

}

int main() {

std::string formatted_time = "2023-03-25 15:30:00"; // 示例时间

time_t timestamp = convert_formatted_time_to_timestamp(formatted_time);

if (timestamp != -1) {

std::cout << "时间戳: " << timestamp << std::endl;

} else {

std::cout << "格式错误" << std::endl;

}

return 0;

}

这段代码定义了一个函数convert_formatted_time_to_timestamp,它接受一个字符串参数,该字符串应该包含按照"年-月-日 时:分:秒"格式给出的时间。函数使用std::get_time来解析字符串,并将解析的时间存储在std::tm结构中。然后,它使用mktime函数将std::tm结构转换为time_t时间戳。如果解析失败,函数返回-1作为错误指示。

main函数中,我们提供了一个示例时间,并输出了相应的时间戳。如果时间格式不正确,则会输出错误信息。

相关推荐
睡美人的小仙女12710 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
rayufo10 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk10 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
数研小生11 小时前
构建命令行单词记忆工具:JSON 词库与艾宾浩斯复习算法的完美结合
算法·json
芒克芒克11 小时前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
缺点内向11 小时前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
一起养小猫11 小时前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl99611 小时前
Java 所有关键字及规范分类
java·开发语言
Python 老手11 小时前
Python while 循环 极简核心讲解
java·python·算法
@Aurora.11 小时前
优选算法【专题九:哈希表】
算法·哈希算法·散列表