阅读量:6
C++ 的标准库 提供了丰富的日期和时间处理功能。以下是一些基本示例,展示了如何使用 C++ 标准库进行时间处理:
- 获取当前时间:
#include
#include
int main() {
std::time_t now = std::time(nullptr);
std::cout << "当前时间: " << std::ctime(&now) << std::endl;
return 0;
}
- 解析时间字符串:
#include
#include
#include
int main() {
std::string time_str = "2021-06-01 12:34:56";
std::tm tm = {};
std::istringstream iss(time_str);
iss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
if (iss.fail()) {
std::cerr << "解析时间字符串失败" << std::endl;
return 1;
}
std::time_t time = std::mktime(&tm);
std::cout << "解析后的时间: " << std::ctime(&time) << std::endl;
return 0;
}
- 格式化时间:
#include
#include
int main() {
std::time_t now = std::time(nullptr);
std::tm* local_time = std::localtime(&now);
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_time);
std::cout << "格式化后的时间: " << buffer << std::endl;
return 0;
}
- 计算时间差:
#include
#include
int main() {
std::time_t now = std::time(nullptr);
std::tm* local_time = std::localtime(&now);
std::time_t later = now + 60 * 60; // 1小时后
std::tm* later_time = std::localtime(&later);
std::cout << "当前时间: " << std::ctime(local_time) << std::endl;
std::cout << "1小时后: " << std::ctime(later_time) << std::endl;
return 0;
}
这些示例展示了如何使用 C++ 标准库进行基本的时间处理。你可以根据需要调整代码以满足特定需求。
以上就是关于“c++ std时间处理如何做”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm