Tulevaisuuden tai menneisyyden päivämäärän laskeminen

C#:
Tulevaisuuden tai menneisyyden päivämäärän laskeminen

How to: (Kuinka tehdä:)

using System;

class DateCalculationExample
{
    static void Main()
    {
        DateTime today = DateTime.Now;
        Console.WriteLine("Today: " + today.ToString("dd.MM.yyyy"));

        DateTime futureDate = today.AddDays(30);
        Console.WriteLine("Date in 30 days: " + futureDate.ToString("dd.MM.yyyy"));

        DateTime pastDate = today.AddDays(-15);
        Console.WriteLine("Date 15 days ago: " + pastDate.ToString("dd.MM.yyyy"));
    }
}

Expected output:

Today: 15.04.2023
Date in 30 days: 15.05.2023
Date 15 days ago: 31.03.2023

Deep Dive (Syväsukellus):

In computing, datetime manipulation is essential for schedules, archives, and time-dependent algorithms. Introduced with .NET Framework, DateTime is a backbone of date calculations in C#. There are methods like AddDays, AddMonths, AddYears for basic date arithmetic.

Alternatives include TimeSpan for precise duration calculations and third-party libraries like NodaTime for robust time zone-aware operations.

When using DateTime, you might encounter DateTimeKind, which indicates whether the date is local, UTC, or unspecified. This affects operations when converting between time zones.

See Also (Katso myös):