Reputation: 71
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.
Upvotes: 2
Views: 1130
Reputation: 1499790
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.
Upvotes: 6
Reputation: 125610
DateTime.Today
returns DateTime
with all time-related properties set to 0. Use DateTime.Now
instead.
Property value
An object that is set to today's date, with the time component set to 00:00:00.
Use MM
in your format to get month. mm
returns minutes. You can check all format specifiers on MSDN: Custom Date and Time Format Strings
Upvotes: 4