Working with Dates

C# Working with Dates

Working with dates and times in C# is facilitated by the DateTime and DateTimeOffset structures, along with methods that allow for date and time manipulation, formatting, and parsing.

Key Concepts

  1. DateTime Structure

Represents dates and times and provides properties and methods for date and time manipulation.

Examples

Creating DateTime Objects

using System;

class Program
{
    static void Main()
    {
        DateTime now = DateTime.Now; // Current date and time
        DateTime specificDate = new DateTime(2024, 12, 25); // Christmas 2024
        DateTime parsedDate = DateTime.Parse("2024-11-19"); // Parsing a date

        Console.WriteLine($"Now: {now}");
        Console.WriteLine($"Specific Date: {specificDate}");
        Console.WriteLine($"Parsed Date: {parsedDate}");
    }
}

Advanced Features

  1. Date and Time Formatting

Format dates and times using standard and custom format strings.

  1. Date and Time Arithmetic

Perform operations like adding or subtracting dates and times.

  1. DateTimeOffset Structure

Represents dates and times with an offset from UTC, useful for dealing with time zones.

  1. Parsing and Validating Dates

Parse strings to DateTime and validate date formats.

Summary

  • DateTime: Basic structure for representing dates and times.

  • DateTimeOffset: For handling dates and times with time zone offsets.

  • Formatting: Use standard and custom formats for date and time representation.

  • Arithmetic: Perform operations like adding or subtracting time spans.

  • Parsing and Validation: Convert strings to DateTime and validate date formats.

Working with dates in C# allows for robust handling of time-related data, critical for applications ranging from scheduling to logging.

Last updated