C++ 日期和时间
作者:野牛程序员:2023-07-10 13:12:33 C++阅读 2839
在C++中,日期和时间操作可以使用 <chrono> 库和 <ctime> 库来实现。下面是一些常见的日期和时间操作的示例代码:
获取当前日期和时间:
#include <chrono>
#include <ctime>
#include <iostream>
int main() {
// 获取当前系统时间
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
// 转换为时间结构
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
// 打印当前日期和时间
std::cout << "当前日期和时间:" << std::ctime(&now_c) << std::endl;
return 0;
}获取特定日期和时间:
#include <chrono>
#include <ctime>
#include <iostream>
int main() {
// 获取当前系统时间
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
// 转换为时间结构
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
// 将时间结构转换为字符串
std::tm* time_info = std::localtime(&now_c);
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", time_info);
// 打印特定日期和时间
std::cout << "特定日期和时间:" << buffer << std::endl;
return 0;
}计算时间间隔:
#include <chrono>
#include <iostream>
int main() {
// 获取起始时间点
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
// 模拟一些操作
for (int i = 0; i < 100000000; ++i) {
// Do something
}
// 获取结束时间点
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
// 计算时间间隔
std::chrono::duration<double> elapsed_seconds = end - start;
// 打印时间间隔
std::cout << "操作耗时:" << elapsed_seconds.count() << " 秒" << std::endl;
return 0;
}这些示例代码演示了如何在C++中使用 <chrono> 和 <ctime> 来处理日期和时间。你可以根据自己的需求进行调整和扩展。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C++ 引用
- 下一篇:C++ 基本的输入输出
