Date Math
Add, subtract, and compare.
Doing Math with Dates
DateTime values are immutable: math never changes the original. Instead, every operation returns a brand new DateTime.
This lesson covers adding and subtracting time, comparing dates, and answering questions like how many days until an event.
AddDays
The AddDays method returns a date that many days later. Pass a negative number to go backward.
Because DateTime is immutable, you must use the returned value; the original stays unchanged.
using System;
class Program
{
static void Main()
{
DateTime d = new DateTime(2024, 3, 5);
DateTime later = d.AddDays(10);
Console.WriteLine(later.ToString("yyyy-MM-dd"));
}
}