Aug 18

DateTime Formatting in C#

The DateTime class is most useful for our time based programs. But most of the time we don’t know how to use the it with appropriate formats.

First of all there are different custom format specifiers for formatting datetime.
list goes like below :

  • y -> (year),
  • M -> (month),
  • d -> (day),
  • h -> (hour 12),
  • H -> (hour 24),
  • m -> (minute),
  • s -> (second),
  • f -> (second fraction),
  • F -> (second fraction, trailing zeroes are trimmed),
  • t -> (P.M or A.M) and last not the list
  • z -> (time zone).

Standard DateTime Formatting

Let’s see some Standard DateTime Formatting. there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.

Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method. propertyPattern value (for en-US culture)
1tShortTimePatternh:mm tt
3TLongTimePatternh:mm:ss tt
4DLongDatePatterndddd, MMMM dd, yyyy
5f(combination of D and t)dddd, MMMM dd, yyyy h:mm tt
6FFullDateTimePatterndddd, MMMM dd, yyyy h:mm:ss tt
7g(combination of d and t)M/d/yyyy h:mm tt
8G(combination of d and T)M/d/yyyy h:mm:ss tt
9m, MMonthDayPatternMMMM dd
10y, YYearMonthPatternMMMM, yyyy
11r, RRFC1123Patternddd, dd MMM yyyy HH’:’mm’:’ss ‘GMT’ (*)
12sSortableDateTi­mePatternyyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss (*)
13uUniversalSorta­bleDateTimePat­ternyyyy’-‘MM’-‘dd HH’:’mm’:’ss’Z’ (*)
(*) = culture independent

As now we are familiar with format specifiers lets we will see two different ways to format datetime

  1. Format by using DateTime.ToString()
  2. Format by using String.Format()

Format DateTime by using DateTime.ToString()

Format DateTime using String.Format()

Let’s see some examples of standard format specifiers in String.Format method and the resulting output.

Permanent link to this article:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.