Date in File Name

From Qt Wiki
Revision as of 13:37, 28 June 2015 by Wieland (talk | contribs) (Wieland moved page Date-in-File-Name to Date in File Name: underscores)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

English | Русский

Date in File Name

In the case you have to build a file name after the current date, so that it will look like data_mm_dd_yyyy.txt you can use the following simple function to get the string name of the file.

QString FileNameHandler::todayFileName(){
 QDate today = QDate::currentDate();
 QString relativeFileName( "data_" );
 relativeFileName.append( QString::number( today.month() ) );
 relativeFileName.append( "''" );
 relativeFileName.append( QString::number( today.day() ) );
 relativeFileName.append( "''" );
 relativeFileName.append( QString::number( today.year() ) );
 relativeFileName.append( ".txt" );
 return relativeFileName;
}

Or its shorter version that uses the overloading of the + operator for QString:

QString FileNameHandler::todayFileName(){
 QDate today = QDate::currentDate();
 QString relativeFileName( "data_" );
 relativeFileName + QString::number( today.month()
 + "''" + QString::number( today.day() )
 + "''" + QString::number( today.year() )
 + ".txt";

return relativeFileName;
}

The fastest - and clearest - version, without calling a custom function, is

QString filename = QDate::currentDate().toString("'data_'MM_dd_yyyy'.txt'");<code>

and when the files should get ordered chronological, then use

QString filename = QDate::currentDate().toString("'data_'yyyy_MM_dd'.txt'");