这篇文章将讨论如何在 C++ 中获取当前时间和日期。
1.使用 std::chrono
从 C++11 开始,在 C++ 中获取当前时间和日期的标准解决方案是使用 chrono 库。我们可以得到当前时间 std::chrono::system_clock::now()
来自 <chrono.h>
标头,并将其转换为 std::time_t
类型(自纪元以来的时间)。然后,转换 std::time_t
到本地日历时间 std::ctime
在 Www Mmm dd hh:mm:ss yyyy
格式,如下图:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <chrono> int main() { auto now = std::chrono::system_clock::now(); std::time_t end_time = std::chrono::system_clock::to_time_t(now); std::cout << "Current Time and Date: " << std::ctime(&end_time) << std::endl; return 0; } |
输出(会有所不同):
Current Time and Date: Tue Feb 08 18:40:13 2018
如果您只需要在 C++ 中测量经过的时间,请执行以下操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <chrono> int main() { auto start = std::chrono::system_clock::now(); // 做一些工作 for (int i = 0; i < 10000000; i++) {} auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::cout << "Elapsed Time: " << elapsed_seconds.count() << " sec" << std::endl; return 0; } |
输出(会有所不同):
Elapsed Time: 0.060156 sec
从 C++20 开始,我们也可以使用 std::chrono::zoned_time 用时区表示日期和时间。
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <chrono> int main() { std::chrono::zoned_time now { std::chrono::current_zone(), std::chrono::system_clock::now() }; std::cout << "Current Time and Date: " << std::endl; return 0; } |
2.使用 std::time
这个想法是获取自纪元以来经过的秒数 std::time_t
值,然后将其转换为 std::tm
实例与 std::localtime
.一个 std::tm
对象保存一个日历日期和时间,分解成它的组成部分(秒、分、小时、日、月、年等)。
下面的代码示例演示了它的用法。请注意,此解决方案需要 <ctime>
标题。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <ctime> int main() { std::time_吨 t = std::time(nullptr); std::tm* now = std::localtime(&t); std::cout << "Current Date: " << now->tm_mday << '/' << (now->tm_mon + 1) << '/' << (now->tm_year + 1900) << std::endl; return 0; } |
输出(会有所不同):
Current Date: 8/2/2018
我们可以进一步将日期和时间信息从 std::tm
对象为空终止的多字节字符,根据指定的格式字符串使用 strftime()
功能。例如,以下代码将当前日期和时间返回为 std::string
在格式 MM-DD-YYYY HH:mm:ss
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <ctime> std::string currentDateTime() { std::time_吨 t = std::time(nullptr); std::tm* now = std::localtime(&t); char buffer[128]; strftime(buffer, sizeof(buffer), "%m-%d-%Y %X", now); return buffer; } int main() { std::cout << "Current Time and Date: " << currentDateTime() << std::endl; return 0; } |
输出(会有所不同):
Current Time and Date: 02-08-2018 18:42:41
3.使用 Boost.Date_Time
另一种选择是使用 日期时间函数 由 boost 库提供。 boost库提供了几种时间系统。以下解决方案使用 boost::posix_time::microsec_clock::universal_time
从标题 <boost/date_time/posix_time/posix_time>
– 返回 UTC 时间。
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <boost/date_time/posix_time/posix_time.hpp> int main() { boost::posix_time::ptime datetime = boost::posix_time::microsec_clock::universal_time(); std::cout << "Current Time and Date: " << datetime << std::endl; return 0; } |
输出(会有所不同):
Current Time and Date: 2018-Feb-08 18:42:41.804879
这就是在 C++ 中获取当前时间和日期的全部内容。