c++qtdatetimeqdatetime

C++ reliable way to get QDateTime for buildtime


Previously I had a question about __DATE__

I want to use __DATE__ to get the build time. The product will be compiled on systems with different locale. Is the format for __DATE__ always the same? My goal is to get the buildtime from __DATE__ and i want to make sure it works on any system. Currently I use:

QDateTime(QLocale("en_US").toDate(QString(__DATE__).simplified(), "MMM d yyyy")).toMSecsSinceEpoch();

To get a datetime of the buildtime. But is it possible that in cases this wont work, e.g. is it possible __DATE__ does not return Jul 14 2020 but in a local format e.g. chinese? If the last is the case the todate method will not work right?


Solution

  • From C++ standard (draft):

    __DATE__

    The date of translation of the source file: a character string literal of the form "Mmm dd yyyy", where the names of the months are the same as those generated by the asctime function, and the first character of dd is a space character if the value is less than 10. If the date of translation is not available, an implementation-defined valid date shall be supplied.

    http://eel.is/c++draft/cpp#predefined-1.2

    The last sentence gives some freedom for compiler what to do if the date is not available. GCC does this:

    If GCC cannot determine the current date, it will emit a warning message (once per compilation) and __DATE__ will expand to "??? ?? ????".

    https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html

    To sum up - the format is fixed and it is always "Mmm dd yyy", using English names.