C has a predefined macro __DATE__
, that shows the date of the compiled source file .
The date is displayed in the format "Mmm dd yyyy" .
Is there any way to be formatted this date, using macros ?
In this format "yyyy Mmm dd".
Instead of being :
Jul 19 2013
Should be :
2013 Jul 19
__FILE__ This macro expands to the name of the current input file, in the form of a C string constant. This is the path by which the preprocessor opened the file, not the short name specified in ' #include ' or as the input file name argument. For example, "/usr/local/include/myheader.
__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.
__STDC__ In normal operation, this macro expands to the constant 1, to signify that this compiler conforms to ISO Standard C. If GNU CPP is used with a compiler other than GCC, this is not necessarily true; however, the preprocessor always conforms to the standard, unless the -traditional option is used.
The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.
In C you could have a macro that generates a compound literal on the fly that has the order that you like, something like
#define FDATE (char const[]){ __DATE__[7], __DATE__[8], ..., ' ', ... , '\0' }
in all places where it matters your optimizer should be able to handle this efficiently.
In case anyone is looking for a way to convert Mmm DD YYYY
into a string YYMMDD
with ASCII digits only (like "220103"
), then here's the code for that. It should work in C and C++ both:
#include <stdio.h>
const char version[6+1] =
{
// YY year
__DATE__[9], __DATE__[10],
// First month letter, Oct Nov Dec = '1' otherwise '0'
(__DATE__[0] == 'O' || __DATE__[0] == 'N' || __DATE__[0] == 'D') ? '1' : '0',
// Second month letter
(__DATE__[0] == 'J') ? ( (__DATE__[1] == 'a') ? '1' : // Jan, Jun or Jul
((__DATE__[2] == 'n') ? '6' : '7') ) :
(__DATE__[0] == 'F') ? '2' : // Feb
(__DATE__[0] == 'M') ? (__DATE__[2] == 'r') ? '3' : '5' : // Mar or May
(__DATE__[0] == 'A') ? (__DATE__[1] == 'p') ? '4' : '8' : // Apr or Aug
(__DATE__[0] == 'S') ? '9' : // Sep
(__DATE__[0] == 'O') ? '0' : // Oct
(__DATE__[0] == 'N') ? '1' : // Nov
(__DATE__[0] == 'D') ? '2' : // Dec
0,
// First day letter, replace space with digit
__DATE__[4]==' ' ? '0' : __DATE__[4],
// Second day letter
__DATE__[5],
'\0'
};
int main(void)
{
puts(__DATE__);
puts(version);
}
Output:
Jan 3 2022
220103
Disassembly (gcc x86_64):
version:
.string "220103"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With