C++ 按日期时间生成文件
在日常开发环境中,需要按照时间去命名文件名,因此需要创建如年-月-日此类的字符串,这里给出例子。
//定义时间命名字符串的格式
enum FileNameStyle
{ //example 2022.07.11 14:54:27
MONTH_DAY_TIME_1 = 0, //07-11-14:54:27.png
MONTH_DAY_TIME_2, //0711-1454-27.png
YEAR_MONTH_DAY_TIME_1, //2022.07.11-14.54.27.png
YEAR_MONTH_DAY_TIME_2, //2022-07-11-14-54-27.png
YEAR_MONTH_DAY_TIME_3 //20220711-14:54:27.png
};
//返回时间字符串
string UpdateFileName(int NameStyle)
{
string FileName;
time_t mNowtime;
time(&mNowtime);
struct tm *mTimePtr;
mTimePtr = localtime(&mNowtime);
string str_year = to_string(mTimePtr->tm_year + 1900);
string str_mon = to_string(mTimePtr->tm_mon + 1);
string str_day = to_string(mTimePtr->tm_mday);
string str_hour = to_string(mTimePtr->tm_hour);
string str_min = to_string(mTimePtr->tm_min);
string str_sec = to_string(mTimePtr->tm_sec);
// add 0 if number samller than 10, 01,02,03...
if (str_mon.size() < 2)
{
str_mon = "0" + str_mon;
}
if (str_min.size() < 2)
{
str_min = "0" + str_min;
}
if (str_sec.size() < 2)
{
str_sec = "0" + str_sec;
}
switch (NameStyle)
{
case MONTH_DAY_TIME_1:
FileName = str_mon + "-" + str_day + "-" + str_hour + ":" + str_min + ":" + str_sec;
break;
case MONTH_DAY_TIME_2:
FileName = str_mon + str_day + "-" + str_hour + str_min + "-" + str_sec;
break;
case YEAR_MONTH_DAY_TIME_1:
FileName = str_year + "." + str_mon + "." + str_day + "-" + str_hour + "." + str_min + "." + str_sec;
break;
case YEAR_MONTH_DAY_TIME_2:
FileName = str_year + "-" + str_mon + "-" + str_day + "-" + str_hour + "-" + str_min + "-" + str_sec;
break;
case YEAR_MONTH_DAY_TIME_3:
FileName = str_year + str_mon + str_day + "-" + str_hour + ":" + str_min + ":" + str_sec;
break;
default:
FileName = str_year + "-" + str_mon + "-" + str_day + "-" + str_hour + "-" + str_min + "-" + str_sec;
break;
}
FileName = FileName + ".png";//添加自己需要的文件尾缀
cout << "FileName is " << FileName << endl;
return FileName;
}
int main()
{
int namestyle = YEAR_MONTH_DAY_TIME_2;
UpdateFileName(namestyle);
return 0;
}