How to format DateTime in C#

In C#, you can format DateTime values using format strings with the ToString() method or string interpolation. Standard format specifiers like "d" for short date or "T" for long time provide common formats.

Custom format strings use patterns like "yyyy-MM-dd" for year-month-day or "HH:mm:ss" for 24-hour time. Use "MM" for months (not "mm" which is minutes).

The format strings are case-sensitive: "MM" is month, "mm" is minutes, "HH" is 24-hour, "hh" is 12-hour format.

C# Example Code
using System;

public class DateTimeFormatting
{
    public static void Main(string[] args)
    {
        DateTime now = DateTime.Now;
        DateTime specificDate = new DateTime(2024, 3, 15, 14, 30, 45);

        // Standard format specifiers
        Console.WriteLine("Standard Formats:");
        Console.WriteLine($"Short date (d): {now:d}");
        Console.WriteLine($"Long date (D): {now:D}");
        Console.WriteLine($"Short time (t): {now:t}");
        Console.WriteLine($"Long time (T): {now:T}");
        Console.WriteLine($"Full date/time (F): {now:F}");
        Console.WriteLine($"General (G): {now:G}");

        // Custom format strings
        Console.WriteLine("\nCustom Formats:");
        Console.WriteLine($"yyyy-MM-dd: {specificDate:yyyy-MM-dd}");
        Console.WriteLine($"MM/dd/yyyy: {specificDate:MM/dd/yyyy}");
        Console.WriteLine($"dd-MMM-yyyy: {specificDate:dd-MMM-yyyy}");
        Console.WriteLine($"HH:mm:ss: {specificDate:HH:mm:ss}");
        Console.WriteLine($"hh:mm tt: {specificDate:hh:mm tt}");

        // Combining date and time
        Console.WriteLine("\nCombined:");
        Console.WriteLine($"ISO 8601: {specificDate:yyyy-MM-ddTHH:mm:ss}");
        Console.WriteLine($"Custom: {specificDate:MMMM dd, yyyy 'at' h:mm tt}");

        // Day and month names
        Console.WriteLine("\nNames:");
        Console.WriteLine($"Day of week: {now:dddd}");
        Console.WriteLine($"Month name: {now:MMMM}");
        Console.WriteLine($"Abbreviated: {now:ddd, MMM dd}");

        // Using ToString method
        Console.WriteLine("\nUsing ToString:");
        Console.WriteLine(now.ToString("yyyy-MM-dd"));
        Console.WriteLine(now.ToString("h:mm:ss tt"));
    }
}