Skip to content

CSharp Basics ConsoleWriteLine DateTime

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Basics: Console.WriteLine and DateTime

This lesson introduces two fundamental building blocks of C# console programs:

  • Console.WriteLine for output
  • DateTime for working with dates and times

Related wiki pages:

  • General C# overview: CSharpBible.md
  • Console helper libraries: CSharpBible-Library-ConsoleLib.md

Official documentation:


1. A simple example

using System;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a DateTime object for a specific date
        DateTime now = new DateTime(2024, 12, 6);  // 6 December 2024

        // Print the date
        Console.WriteLine("Today is: {0}", now);
    }
}

Explanation:

  1. using System; – Imports the System namespace with basic types like Console and DateTime.
  2. public class Example – Defines a class named Example.
  3. public static void Main(string[] args) – Entry point of the program.
  4. new DateTime(2024, 12, 6) – Constructs a specific date.
  5. Console.WriteLine("Today is: {0}", now); – Writes formatted text to the console.

2. Running the program (SDK-style)

With the .NET SDK you typically use a project instead of calling csc directly:

  1. Create a new console app:
    • dotnet new console -n DateTimeSample
  2. Replace the contents of Program.cs with the example above.
  3. Run:
    • dotnet run

You should see something like:

Today is: 06.12.2024 00:00:00

The exact format depends on your system culture.


3. Formatting DateTime

You can format dates using ToString with format strings:

DateTime now = DateTime.Now;

Console.WriteLine(now.ToString("yyyy-MM-dd"));      // 2024-12-06
Console.WriteLine(now.ToString("dd.MM.yyyy"));      // 06.12.2024
Console.WriteLine(now.ToString("O"));               // ISO 8601

See the DateTime docs for a full list of standard and custom format strings.


4. Next steps

  • Use Console.ReadLine to read user input and print it back.
  • Combine Console I/O with control structures shown in other lessons in this wiki (see CSharpBible.md for navigation).
  • Explore helper utilities in CSharpBible-Library-ConsoleLib.md if available.

Clone this wiki locally