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

相关推荐
Dxy12393102161 小时前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
故事和你913 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__3 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__3 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
techdashen4 小时前
Rust项目公开征测:Cargo 构建目录新布局方案
开发语言·后端·rust
星空椰4 小时前
JavaScript 进阶基础:函数、作用域与常用技巧总结
开发语言·前端·javascript
忒可君4 小时前
C# winform 自制分页功能
android·开发语言·c#
Rust研习社4 小时前
Rust 智能指针 Cell 与 RefCell 的内部可变性
开发语言·后端·rust
王老师青少年编程4 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程4 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果