date time format in csharp

To format a DateTime object in C#, you can use the ToString() method with a format string.

Here are some common format specifiers:

  • d or D: short or long date pattern
  • t or T: short or long time pattern
  • f or F: full date/time pattern (short time)
  • g or G: general date/time pattern (short time)
  • s or S: sortable date/time pattern (ISO 8601)
  • u or U: universal sortable date/time pattern (UTC Format)

You can also use custom format strings to specify your own date/time format.

Here's an example of how to format a DateTime object as a string using a predefined format specifier:

main.cs
DateTime now = DateTime.Now;

string shortDate = now.ToString("d");          // Output: "6/2/2022"
string longDate = now.ToString("D");           // Output: "Thursday, June 2, 2022"
string shortTime = now.ToString("t");          // Output: "11:27 PM"
string longTime = now.ToString("T");           // Output: "11:27:45 PM"
string fullDateTimeShortTime = now.ToString("f");  // Output: "Thursday, June 2, 2022 11:27 PM"
string generalDateTimeShortTime = now.ToString("g");  // Output: "6/2/2022 11:27 PM"
string sortableDateTime = now.ToString("s");   // Output: "2022-06-02T23:27:45"
string universalSortableDateTime = now.ToString("u");  // Output: "2022-06-02 23:27:45Z"
673 chars
11 lines

And here's an example of how to use a custom format string:

main.cs
string customFormat = now.ToString("yyyy-MM-dd HH:mm:ss");  // Output: "2022-06-02 23:27:45"
93 chars
2 lines

Keep in mind that the formatting options are case-sensitive, so d and D produce different results.

Note: The format specifiers listed above are just a few examples. For more information, you can refer to the official documentation on custom date and time format strings in C#:

related categories

gistlibby LogSnag