简体   繁体   中英

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.

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.

  1. 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.

    from DateTime.Today Property

  2. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM