C# Date/Time Formatting

Using C#, I am trying to format a date in to the following string format: YYYYMMDD_HHMM.xlsx

Here is my code:

DateTime.Today.AddDays(0).ToString("yyyymmdd") + "_" + DateTime.Today.AddDays(0).ToString("hhmm")

Here is my output:

20130027_1200.xlsx

Month is not correct, nor is the time.

Jon Skeet
people
quotationmark

You're using mm, which is minutes, not months - and you're trying to print the time using DateTime.Today, which always returns midnight at the start of the day.

It's not clear why you're adding 0 days, either. I'd use:

DateTime now = DateTime.Now;
string name = now.ToString("yyyyMMdd'_'HHmm'.xlsx'");

(The ' quoting for the _ isn't strictly necessary, but personally I find it simplest to take the approach of quoting everything that isn't a format specifier.)

Or:

DateTime now = DateTime.Now;
string name = string.Format("{0:yyyyMMdd}_{0:HHmm}.xlsx", now);

Note the use of HH instead of hh to get a 24-hour clock rather than 12-hour, too.

Additionally, consider using UtcNow instead of Now, depending on your requirements. Note that around daylight saving transitions, the clock will go back or forward, so you could end up with duplicate file names.

Also note how in my code I've used DateTime.Now once - with your original code, you were finding the current date twice, which could have given different results on each invocation.

Finally, you might also want to specify CultureInfo.InvariantCulture when you format the date/time - otherwise if the current culture is one which doesn't use a Gregorian calendar by default, you may not get the results you were expecting.

people

See more on this question at Stackoverflow