在Qt发布程序时,有时想将版本号信息加上编译时间添加到程序右下角。
- 利用__DATE__与__TIME__编译宏特性为Qt程序添加编译日期时间。
-
__DATE__
和__TIME__
是C/C++语言中的预定义宏,它们分别用于获取当前源文件被编译的日期和时间。 -
__DATE__
宏返回一个字符串常量,表示当前源文件被编译的日期。日期的格式为 “MMM DD YYYY”,其中MMM表示月份的缩写,DD表示日期,YYYY表示年份的四位数。例如,“Sep 05 2023” 表示2023年9月5日。 -
__TIME__
宏返回一个字符串常量,表示当前源文件被编译的时间。时间的格式为 “HH:MM:SS”,其中HH表示小时,MM表示分钟,SS表示秒钟。例如,“01:30:04” 表示01时30分04秒。
这两个宏在编写代码时可以用于输出编译时的日期和时间信息。通常用于日志记录、版本信息等场景中,有助于追踪代码的更新和维护。注意,它们提供的是编译时的日期和时间,并不是运行时的实际日期和时间。
注意:***QDateTime::currentDateTime()***是获取当前时间的,不是获取编译时间的。
以下是具体实现
static const QString buildTime()
{
QString dateTime;
dateTime.clear();
dateTime += __DATE__;
dateTime += __TIME__;
//注意" "是两个空格,用于日期为单数时需要转成“空格+0”
dateTime.replace(" "," 0");
QDateTime buildDateTime = QLocale(QLocale::English).toDateTime(dateTime,"MMM dd yyyyhh:mm:ss");
QString strMonth, strDay, strHour;
int nMonth = buildDateTime.date().month();
if(nMonth < 10)
{
strMonth = QString("0%1").arg(nMonth);
}else{
strMonth = QString("%1").arg(nMonth);
}
int nDay = buildDateTime.date().day();
if(nDay < 10)
{
strDay = QString("0%1").arg(nDay);
}else{
strDay = QString("%1").arg(nDay);
}
int nHour = buildDateTime.time().hour();
if(nHour < 10)
{
strHour = QString("0%1").arg(nHour);
}else{
strHour = QString("%1").arg(nHour);
}
QString strBuildTime;
strBuildTime = QString("%1-%2-%3 %4:%5:%6").arg(buildDateTime.date().year()).arg(strMonth).arg(strDay).arg(strHour).arg(buildDateTime.time().minute()).arg(buildDateTime.time().second());
return strBuildTime;
}