C ++在编译时将月份作为数字 [英] C++ get the month as number at compile time

查看:124
本文介绍了C ++在编译时将月份作为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c ++项目,该项目必须打印一个修订字符串.修订字符串是公司明智地指定的,并且协议包括生成时间yyyy/mm/dd.

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).

我正在尝试通过从编译器获取构建日期来实现这一点,但是__DATE____TIMESTAMP__给出了以毫米为单位的月份.

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");

谢谢

推荐答案

我认为以下宏符合您的要求.在这里,我们正在处理本月的第三个字母,因为它在大多数月份中都是唯一的(1月/6月,3月/4月除外),因此比较容易.

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)

这篇关于C ++在编译时将月份作为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆