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

相关推荐
励志不掉头发的内向程序员1 小时前
【从零写一个CAD 03】三个 double 值得单独一个类吗:把视图变换抽成 View
开发语言·c++·qt·学习·系统架构
PHP实战开发录2 小时前
PHP接口大整数为什么变了
开发语言·php
Doubbbbbbble云2 小时前
基于贪心算法的区间覆盖问题求解策略4
算法·贪心算法
临床数据科学和人工智能兴趣组5 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
不会就选b8 小时前
算法日常・每日刷题--<贪心>25
数据结构·算法
andyweike8 小时前
php笔记
开发语言·笔记·php
蒸蒸yyyyzwd8 小时前
秋招学习笔记 day46
c++·八股
Circ.9 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
现任明教教主~11 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou14113611 小时前
SpringSecurity_02_授权与高级功能
开发语言·python