Some examples and tips on C# DateTime formatting using string.Format() or .ToString() methods.
Standard formats are typically used when you need a fast string representation of your DateTime object based on current culture.
DateTime date = DateTime.Now;
// Short date:
string.Format("{0:d}", date) // 7/4/2022
// Long date:
string.Format("{0:D}", date) // Monday, July 4, 2022
// Short time:
string.Format("{0:t}", date) // 11:01 PM
// Long time:
string.Format("{0:T}", date) // 11:01:58 PM
// Full date/time (short time):
string.Format("{0:f}", date) // Monday, July 4, 2022 11:01 PM
// Full date/time (long time):
string.Format("{0:F}", date) // Monday, July 4, 2022 11:01:58 PM
// General date/time (long time):
string.Format("{0:g}", date) // 7/4/2022 11:01 PM
// General date/time (long time):
string.Format("{0:G}", date) // 7/4/2022 11:01:58 PM
// Sortable date/time:
string.Format("{0:s}", date) // 2022-07-04T23:01:58
Custom formats are useful when you need more flexibility on the output string format.
DateTime date = DateTime.Now;
string.Format("{0:MM/dd/yyyy}", date) // 07/04/2022
string.Format("{0:MMMM dd, yyyy}", date)// July 04, 2022
string.Format("{0:MMM yyyy}", date) // Jul 2022
string.Format("{0:hh:mm tt}", date) // 11:01 PM
// Year patterns:
string.Format("{0:yy yyy yyyy}", date) // 22 2022 2022
// Month patterns:
string.Format("{0:MM MMM MMMM}", date) // 07 Jul July
// Day patterns:
string.Format("{0:dd ddd dddd}", date) // 04 Mon Monday
// Hour
string.Format("{0:hh HH tt}", date) // 11 23 PM
// Minute, second, second fraction
string.Format("{0:mm ss ffff}", date) // 01 58 5784
When you format a DateTime with DateTime.ToString() you can also specify the culture to use.
using System.Globalization;
// ...
DateTime date = DateTime.Now;
// InvariantCulture
CultureInfo invC = CultureInfo.InvariantCulture;
date.ToString("f", invC) // Monday, 04 July 2022 23:01
date.ToString("d", invC) // 07/04/2022
date.ToString("t", invC) // 23:01
// German CultureInfo
CultureInfo deC = new CultureInfo("de-De");
date.ToString("f", deC) // Montag, 4. Juli 2022 23:01
date.ToString("d", deC) // 04.07.2022
date.ToString("t", deC) // 23:01
// French CultureInfo
CultureInfo frC = new CultureInfo("fr-FR");
date.ToString("f", frC) // lundi 4 juillet 2022 23:01
date.ToString("d", frC) // 04/07/2022
date.ToString("t", frC) // 23:01
// Spanish CultureInfo
CultureInfo esC = new CultureInfo("es-ES");
date.ToString("f", esC) // lunes, 4 de julio de 2022 23:01
date.ToString("d", esC) // 04/07/2022
date.ToString("t", esC) // 23:01
Any characters not used by the formatter is reported in the result string. If you need to enter text with reserved characters that must be inserted between two ' (single quote).
DateTime date = DateTime.Now;
// Escaped date text
string.Format("{0:'y:' yyyy' m:' M 'd:' d}", date) // y: 2022 m: 7 d: 4
// Force time format to use ':' as separator ()
string.Format("{0:HH':'mm}", date) // 23:01
A simple tool for test your format string.