1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <ctime>
#include <string>
std::string format( int year, int month, int day, char flag = 'D' )
{
std::tm tm {} ;
tm.tm_year = year - 1900 ;
tm.tm_mon = month - 1 ;
tm.tm_mday = day ;
std::string fmt ;
if( flag == 'T' || flag == 't' ) fmt = "%m/%d/%y" ; // month/day/year
else if( flag == 'L' || flag == 'l' ) fmt = "%A %B %d, %Y" ; // long
if( !fmt.empty() )
{
char buffer[128] ;
std::strftime( buffer, sizeof(buffer), fmt.c_str(), std::addressof(tm) ) ;
return buffer ;
}
else return std::to_string(month) + '/' + std::to_string(day) + '/' + std::to_string(year) ;
}
int main()
{
const int year = 2017 ;
const int month = 9 ;
const int day = 30 ;
std::cout << "default: " << format( year, month, day ) << '\n' // default: 9/30/2017
<< " short: " << format( year, month, day, 'T' ) << '\n' // short: 09/30/17
<< " long: " << format( year, month, day, 'L' ) << '\n' ; // long: Sunday September 30, 2017
}
|