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

相关推荐
炸膛坦客15 分钟前
单片机/C/C++八股:(二十一)include <> 和 include ““ 的区别
c语言·c++
Yupureki23 分钟前
《Linux系统编程》12.基础IO
linux·运维·c语言·开发语言·数据库·c++
淮北49423 分钟前
bash下好用的快捷键以及linux常用指令
linux·开发语言·ubuntu·bash
Jordannnnnnnn24 分钟前
追赶32名
c++
炸膛坦客25 分钟前
单片机/C/C++八股:(十八)C/C++ 中 sizeof 和 strlen 的区别
c语言·c++
XiYang-DING40 分钟前
【LeetCode】LCR 019. 验证回文串 II
算法·leetcode·职场和发展
薛定谔的猫喵喵41 分钟前
卸载 Python 3.8 报错 “Could not set file security” 的终极解决方案
开发语言·python
灰色小旋风42 分钟前
力扣18 四数之和(C++)
数据结构·算法·leetcode
噜啦噜啦嘞好1 小时前
算法篇:前缀和
数据结构·算法