0
0
CsharpHow-ToBeginner · 3 min read

How to Add Days to Date in C# - Simple Guide

In C#, you can add days to a date using the DateTime.AddDays method. This method returns a new DateTime object with the specified number of days added to the original date.
📐

Syntax

The DateTime.AddDays method adds a specified number of days to a DateTime object and returns a new DateTime object. The original date is not changed.

  • days: A double value representing the number of days to add. It can be positive (to add days) or negative (to subtract days).
  • Returns: A new DateTime object with the days added.
csharp
DateTime newDate = originalDate.AddDays(days);
💻

Example

This example shows how to add 5 days to the current date and print both the original and the new date.

csharp
using System;

class Program
{
    static void Main()
    {
        DateTime today = DateTime.Now;
        DateTime futureDate = today.AddDays(5);

        Console.WriteLine($"Today: {today:yyyy-MM-dd}");
        Console.WriteLine($"Date after 5 days: {futureDate:yyyy-MM-dd}");
    }
}
Output
Today: 2024-06-15 Date after 5 days: 2024-06-20
⚠️

Common Pitfalls

One common mistake is trying to modify the original DateTime object directly. DateTime is immutable, so AddDays returns a new object and does not change the original.

Another pitfall is passing an invalid number of days, such as a very large number that causes an overflow.

csharp
using System;

class Program
{
    static void Main()
    {
        DateTime date = DateTime.Now;

        // Wrong: This does NOT change 'date'
        date.AddDays(3);
        Console.WriteLine($"Date after AddDays without assignment: {date:yyyy-MM-dd}");

        // Right: Assign the result to a variable
        date = date.AddDays(3);
        Console.WriteLine($"Date after AddDays with assignment: {date:yyyy-MM-dd}");
    }
}
Output
Date after AddDays without assignment: 2024-06-15 Date after AddDays with assignment: 2024-06-18
📊

Quick Reference

MethodDescriptionExample
AddDays(double days)Adds specified days to a DateTime and returns new DateTimedate.AddDays(5)
AddDays(-double days)Subtracts specified days from a DateTimedate.AddDays(-3)

Key Takeaways

Use DateTime.AddDays to add or subtract days from a date in C#.
DateTime is immutable; always assign the result of AddDays to a variable.
AddDays accepts positive or negative double values for days.
Avoid modifying the original DateTime without assignment.
Check for overflow if adding very large day values.