Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ get the month as number at compile time

I have a c++ project that has to print a revision string. The revision string is company wise specified and the protocol includes the build time as yyyy/mm/dd.

I use to specify this as macro from the build system, but this is no longer an option because messes up the precompiled headers (in incremental build when the day changes).

I am trying to implement this with obtaining the build date from the compiler but __DATE__ and __TIMESTAMP__ give the month in Mmm.

Any ideas how I can take the month as number?


based on the answer below the version I finish with is:

#define __MONTH__ (\
  __DATE__ [2] == 'n' ? (__DATE__ [1] == 'a' ? "01" : "06") \
: __DATE__ [2] == 'b' ? "02" \
: __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M' ? "03" : "04") \
: __DATE__ [2] == 'y' ? "05" \
: __DATE__ [2] == 'l' ? "07" \
: __DATE__ [2] == 'g' ? "08" \
: __DATE__ [2] == 'p' ? "09" \
: __DATE__ [2] == 't' ? "10" \
: __DATE__ [2] == 'v' ? "11" \
: "12")

...

std::string udate = __DATE__;
std::string date = udate.substr(7, 4) + "/" + __MONTH__ + "/" + udate.substr(4, 2);
boost::replace_all(date, " ", "0");

thanks

like image 609
gsf Avatar asked Jan 12 '23 00:01

gsf


1 Answers

I think the below macro matches your requirements. Here we are working on the 3rd letter of the month, since it is unique for most of the months (except Jan/Jun, March/April), hence easier for comparison.

#define MONTH (\
  __DATE__ [2] == 'n' ? (__DATE__ [1] == 'a' ? 1 : 6) \
: __DATE__ [2] == 'b' ? 2 \
: __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M' ? 3 : 4) \
: __DATE__ [2] == 'y' ? 5 \
: __DATE__ [2] == 'l' ? 7 \
: __DATE__ [2] == 'g' ? 8 \
: __DATE__ [2] == 'p' ? 9 \
: __DATE__ [2] == 't' ? 10 \
: __DATE__ [2] == 'v' ? 11 \
: 12)
like image 93
lolando Avatar answered Jan 27 '23 13:01

lolando