是否可以在编译时获取当前时间?
Is it possible to get current time at compile time?
我正在考虑使用当前时间戳作为一个版本。我想在编译时检索该信息。所以理想情况下我想这样做:
constexpr long long currentTimestamp = getCurrentTimestamp();
C++14 可以吗?
使用 standard C __TIME__
宏和 __DATE__
宏。
有关示例,请参阅 this 问题。
使用__DATE__
和__TIME__
或__TIMESTAMP__
:
#include <stdio.h>
int main()
{
printf("date: '%s'\n", __DATE__);
printf("time: '%s'\n", __TIME__);
printf("timestamp: '%s'\n", __TIMESTAMP__);
}
date: 'May 5 2017'
time: '00:29:26'
timestamp: 'Fri May 5 00:29:26 2017'
但是,出于显而易见的原因,您需要确保重新编译该文件。
来自 gcc online docs:
__DATE__
This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains
eleven characters and looks like "Feb 12 1996". If the day of the
month is less than 10, it is padded with a space on the left.
__TIME__
This macro expands to a string constant that describes the time at which the preprocessor is being run. The string constant contains
eight characters and looks like "23:59:01".
__TIMESTAMP__
This macro expands to a string constant that describes the date and time of the last modification of the current source file. The
string constant contains abbreviated day of the week, month, day of
the month, time in hh:mm:ss form, year and looks like "Sun Sep 16
01:03:52 1973". If the day of the month is less than 10, it is padded
with a space on the left.
请注意,__TIMESTAMP__
不是标准的,某些编译器可能不支持它。
我正在考虑使用当前时间戳作为一个版本。我想在编译时检索该信息。所以理想情况下我想这样做:
constexpr long long currentTimestamp = getCurrentTimestamp();
C++14 可以吗?
使用 standard C __TIME__
宏和 __DATE__
宏。
有关示例,请参阅 this 问题。
使用__DATE__
和__TIME__
或__TIMESTAMP__
:
#include <stdio.h>
int main()
{
printf("date: '%s'\n", __DATE__);
printf("time: '%s'\n", __TIME__);
printf("timestamp: '%s'\n", __TIMESTAMP__);
}
date: 'May 5 2017'
time: '00:29:26'
timestamp: 'Fri May 5 00:29:26 2017'
但是,出于显而易见的原因,您需要确保重新编译该文件。
来自 gcc online docs:
__DATE__
This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains eleven characters and looks like "Feb 12 1996". If the day of the month is less than 10, it is padded with a space on the left.
__TIME__
This macro expands to a string constant that describes the time at which the preprocessor is being run. The string constant contains eight characters and looks like "23:59:01".
__TIMESTAMP__
This macro expands to a string constant that describes the date and time of the last modification of the current source file. The string constant contains abbreviated day of the week, month, day of the month, time in hh:mm:ss form, year and looks like "Sun Sep 16 01:03:52 1973". If the day of the month is less than 10, it is padded with a space on the left.
请注意,__TIMESTAMP__
不是标准的,某些编译器可能不支持它。