C++中实现string与time互相转换,可以使用库中的std::get_time和std::put_time函数。
在C++中,我们可以使用标准库中的<string>和<chrono>来实现string与time的互相转换,下面将详细介绍如何实现这两种转换。
string转time
要将string转换为time,我们需要使用std::get_time函数,这个函数可以将一个表示时间的字符串转换为一个std::tm结构体对象,我们需要包含<iomanip>头文件,然后使用std::get_time函数进行转换。

示例代码:
include <iostream>
include <sstream>
include <iomanip>
include <ctime>
include <string>
int main() {
std::string time_str = "2022-01-01 12:00:00";
std::tm tm = {};
std::istringstream ss(time_str);
ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
if (ss.fail()) {
std::cout << "Failed to convert string to time" << std::endl;
return 1;
}
std::time_t time_t_value = std::mktime(&tm);
std::cout << "Converted time: " << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << std::endl;
std::cout << "Time_t value: " << time_t_value << std::endl;
return 0;
}
time转string
要将time转换为string,我们可以使用std::put_time函数,这个函数可以将一个std::tm结构体对象转换为一个表示时间的字符串,我们需要包含<iomanip>头文件,然后使用std::put_time函数进行转换。
示例代码:

include <iostream>
include <ctime>
include <iomanip>
include <sstream>
include <string>
int main() {
std::tm tm = {};
std::time_t time_t_value = std::time(nullptr);
std::localtime_r(&time_t_value, &tm);
std::string time_str = std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
std::cout << "Original time: " << std::asctime(&tm) << std::endl;
std::cout << "Converted string: " << time_str << std::endl;
return 0;
}
注意事项
1、在使用std::get_time和std::put_time函数时,需要指定输入输出的时间格式。"%Y-%m-%d %H:%M:%S"表示年-月-日 时:分:秒,更多格式选项可以参考C++文档。
2、std::get_time和std::put_time函数默认使用C语言风格的日期和时间格式,如果需要使用其他风格,可以使用std::gmtime_r和std::localtime_r函数替换std::localtime和std::gmtime函数,这两个函数的第一个参数是一个指向std::tm结构体的指针,第二个参数是可选的,用于设置时区。"%A, %B %d, %Y %I:%M:%S %p"表示星期几,月份 日期,年份 小时:分钟:秒 AM/PM,更多格式选项可以参考C++文档。
3、如果输入的字符串无法转换为有效的时间,std::get_time函数会返回失败状态,在这种情况下,可以使用fail()函数检查转换是否成功,如果转换失败,可以输出错误信息并返回非零值。

4、std::mktime函数可以将一个std::tm结构体对象转换为一个表示时间的整数(time_t类型),这个整数表示从1970年1月1日午夜开始经过的秒数,注意,这个整数在不同的平台上可能有不同的表示范围,在跨平台使用时需要注意数据类型的兼容性。
本文来自投稿,不代表重蔚自留地立场,如若转载,请注明出处https://www.cwhello.com/484892.html
如有侵犯您的合法权益请发邮件951076433@qq.com联系删除