0
0
CsharpHow-ToBeginner · 4 min read

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., mm for minutes instead of MM for 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#:

FormatDescriptionExample Output
yyyy4-digit year2024
MM2-digit month06
dd2-digit day15
HH24-hour clock hour14
hh12-hour clock hour02
mmMinutes30
ssSeconds45
MMMMFull month nameJune
dddAbbreviated day nameSat

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.