CodeBlanks Logo Icon CodeBlanks

Date helpers

C# course · Intermediate · Lesson 22/116

Add DateTime processing methods.

Date helpers

Our third helper is FormatDate: it turns a DateTime value into a consistent text form. Declaration: public static string FormatDate(DateTime date). In the body we use date.ToString("yyyy-MM-dd") to produce ISO format.

Example: Helpers.FormatDate(new DateTime(2024, 3, 15)) returns "2024-03-15". This format is sortable, human-readable, and machine-parseable. Keeping the date format in one place ensures consistency across the application.

DateTime formatting

The ToString method of DateTime takes a format string. yyyy gives a four-digit year, MM a two-digit month, dd a two-digit day. Case matters: MM is month, mm is minute.

The ISO 8601 standard yyyy-MM-dd is common in international commerce and databases. Local formats (e.g. dd.MM.yyyy) may be shown to users, but ISO is safe for storage and transfer.

Exercise Add the FormatDate method and call it

The Helpers class below already has Capitalize and Clamp. Now add a public static string FormatDate(DateTime date) method. In the body write return date.ToString("yyyy-MM-dd");. Inside Main print Helpers.FormatDate(new DateTime(2024, 3, 15)).

Show example solution
Add the FormatDate method to Helpers. In Main write Console.WriteLine(Helpers.FormatDate(new DateTime(2024, 3, 15)));
Example solution:
using System;

static class Helpers
{
    public static string Capitalize(string text)
    {
        if (string.IsNullOrEmpty(text)) return text;
        return char.ToUpper(text[0]) + text.Substring(1);
    }

    public static int Clamp(int value, int min, int max)
    {
        if (value < min) return min;
        if (value > max) return max;
        return value;
    }

    public static string FormatDate(DateTime date)
    {
        return date.ToString("yyyy-MM-dd");
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Ready");
        Console.WriteLine(Helpers.Capitalize("hello"));
        Console.WriteLine(Helpers.Clamp(15, 0, 10));
        Console.WriteLine(Helpers.FormatDate(new DateTime(2024, 3, 15)));
    }
}

Test yourself

  1. Match each format to its output

    yyyy-MM-dd
    2024-03-15
    dd/MM/yyyy
    15/03/2024
    HH:mm
    14:30
    yyyy
    2024
  2. Which is the ISO date format?

    • dd/MM/yyyy
    • MM-dd-yyyy
    • yyyy-MM-dd
    • yyyy:MM:dd
    Show answer

    yyyy-MM-dd — Correct. yyyy-MM-dd is the ISO 8601 standard.

  3. Complete the FormatDate body

    return date.ToString("____");
    Show answer
    return date.ToString("yyyy-MM-dd");

All lessons in Intermediate