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

相关推荐
saltymilk15 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥16 小时前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工1 天前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农1 天前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++