Martin
Martin

Reputation: 3472

How to get date in YYYYMMDD format using winapi

time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
char dateNow[100];
sprintf(dateNow, "%d%d%d", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
int idateNow = atoi(dateNow);  

If the date today is 2014February14, idateNow == 2014214(YYYYMDD). However the required format is 20140214. What minimum change in the above code can attain this.

Upvotes: 0

Views: 1579

Answers (1)

Adrian McCarthy
Adrian McCarthy

Reputation: 47962

printf and friends can use format modifiers to request things like leading zeros. In your case, the format string should be "%04d%02d%02d". The 0s in there say you want leading zeros and the other digits say how many digits you want (minimum).

Since you tagged this as a WinAPI question, I'll point out that there are also Windows-specific functions for formatting dates, such as GetDateFormatEx. (Don't be confused by the name: it actually formats a date rather than fetching a date format.) GetDateFormatEx is a little complicated to use because it can do a lot of things, including applying the user's preferred date format. If you specifically need the yyyymmdd format, then you'd override the user's default date format by providing a "picture string" like "yyyyMMdd".

Upvotes: 4

Related Questions