Back to Home

C# DateTime.ToString Format Cookbook

If you need a quick answer for DateTime.ToString formats, start with the patterns that are most useful in real apps: sortable dates, ISO 8601 timestamps, log output, and filename-safe values.

Common patterns

C# Example Code
DateTime value = new(2024, 3, 15, 14, 30, 45);

Console.WriteLine(value.ToString("yyyy-MM-dd"));          // 2024-03-15
Console.WriteLine(value.ToString("yyyyMMdd"));            // 20240315
Console.WriteLine(value.ToString("yyyy-MM-ddTHH:mm:ss")); // 2024-03-15T14:30:45
Console.WriteLine(value.ToString("HH:mm:ss"));            // 14:30:45
Console.WriteLine(value.ToString("hh:mm tt"));            // 02:30 PM

For logs and filenames

C# Example Code
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("yyyy-MM-dd HH:mm:ss")); // 2024-03-15 14:30:45
Console.WriteLine(now.ToString("yyyyMMdd_HHmmss"));      // 20240315_143045

Use yyyyMMdd_HHmmss when you need a filename-safe stamp without colons or slashes.

UTC and round-trip formats

C# Example Code
DateTime utc = DateTime.UtcNow;
Console.WriteLine(utc.ToString("u")); // 2024-03-15 14:30:45Z
Console.WriteLine(utc.ToString("o")); // 2024-03-15T14:30:45.0000000Z

FAQ

Which format should I use for APIs?

Use o or s for round-trip, machine-readable timestamps.

Which format should I use for files?

Use yyyyMMdd_HHmmss or yyyy-MM-dd depending on whether you want readability or strict sorting.

Take It Further

C# 12 and .NET 8 book cover

The most comprehensive book covering C# 12 and .NET 8 from scratch to production.

C# 12 and .NET 8 — Modern Cross-Platform Development · Mark J. Price

Get it on Amazon →

As an Amazon Associate I earn from qualifying purchases.