How to Format Date in C#: Simple Guide with Examples
In C#, you format dates using the
DateTime.ToString() method with format strings. You can use standard formats like "yyyy-MM-dd" or custom patterns to display dates as you want.Syntax
The basic syntax to format a date in C# is using the DateTime.ToString() method with a format string.
DateTime.ToString(string format): Converts the date to a string using the specified format.format: A string that defines how the date should appear, using format specifiers.
csharp
string formattedDate = DateTime.Now.ToString("yyyy-MM-dd");Example
This example shows how to format the current date and time in different ways using standard and custom format strings.
csharp
using System; class Program { static void Main() { DateTime now = DateTime.Now; string format1 = now.ToString("yyyy-MM-dd"); string format2 = now.ToString("dd/MM/yyyy HH:mm:ss"); string format3 = now.ToString("MMMM dd, yyyy"); Console.WriteLine(format1); Console.WriteLine(format2); Console.WriteLine(format3); } }
Output
2024-06-15
15/06/2024 14:30:45
June 15, 2024
Common Pitfalls
Common mistakes when formatting dates in C# include:
- Using incorrect format specifiers (e.g.,
mmfor minutes instead ofMMfor months which is case-sensitive). - Not considering culture settings which affect month and day names.
- Confusing 12-hour (
hh) and 24-hour (HH) formats.
Here is an example showing a wrong and correct format:
csharp
using System; class Program { static void Main() { DateTime now = DateTime.Now; // Wrong: 'mm' means minutes, not months string wrongFormat = now.ToString("yyyy-mm-dd"); // Correct: 'MM' means months string correctFormat = now.ToString("yyyy-MM-dd"); Console.WriteLine("Wrong format: " + wrongFormat); Console.WriteLine("Correct format: " + correctFormat); } }
Output
Wrong format: 2024-30-15
Correct format: 2024-06-15
Quick Reference
Here are some common date format specifiers in C#:
| Format | Description | Example Output |
|---|---|---|
| yyyy | 4-digit year | 2024 |
| MM | 2-digit month | 06 |
| dd | 2-digit day | 15 |
| HH | 24-hour clock hour | 14 |
| hh | 12-hour clock hour | 02 |
| mm | Minutes | 30 |
| ss | Seconds | 45 |
| MMMM | Full month name | June |
| ddd | Abbreviated day name | Sat |
Key Takeaways
Use DateTime.ToString() with format strings to display dates as needed.
Format specifiers are case-sensitive; 'MM' is months, 'mm' is minutes.
Be aware of culture settings affecting month and day names.
Use 'HH' for 24-hour and 'hh' for 12-hour time formats.
Test your format strings to avoid common mistakes.