C# program to display the previous day

To display the previous day in C#, use the AddDays() method with a value of -1. This method allows you to add or subtract days from a DateTime object.

Syntax

Following is the syntax for getting the current date −

DateTime.Today

Following is the syntax for getting the previous day using AddDays()

DateTime.Today.AddDays(-1)

Using DateTime.Today.AddDays(-1)

The DateTime.Today property returns the current date with the time set to midnight. The AddDays(-1) method subtracts one day from this date −

using System;

public class Demo {
   public static void Main() {
      Console.WriteLine("Today = {0}", DateTime.Today);
      Console.WriteLine("Previous Day = {0}", DateTime.Today.AddDays(-1));
   }
}

The output of the above code is −

Today = 9/4/2018 12:00:00 AM
Previous Day = 9/3/2018 12:00:00 AM

Using DateTime.Now.AddDays(-1)

You can also use DateTime.Now to include the current time along with the date −

using System;

public class Demo {
   public static void Main() {
      DateTime currentDateTime = DateTime.Now;
      DateTime previousDay = currentDateTime.AddDays(-1);
      
      Console.WriteLine("Current Date and Time = {0}", currentDateTime);
      Console.WriteLine("Previous Day = {0}", previousDay);
   }
}

The output of the above code is −

Current Date and Time = 9/4/2018 3:25:47 PM
Previous Day = 9/3/2018 3:25:47 PM

Formatting the Previous Day Output

You can format the previous day output using the ToString() method with format specifiers −

using System;

public class Demo {
   public static void Main() {
      DateTime today = DateTime.Today;
      DateTime previousDay = today.AddDays(-1);
      
      Console.WriteLine("Today: {0}", today.ToString("yyyy-MM-dd"));
      Console.WriteLine("Previous Day: {0}", previousDay.ToString("yyyy-MM-dd"));
      Console.WriteLine("Previous Day (Full): {0}", previousDay.ToString("dddd, MMMM dd, yyyy"));
   }
}

The output of the above code is −

Today: 2018-09-04
Previous Day: 2018-09-03
Previous Day (Full): Monday, September 03, 2018

Conclusion

The AddDays(-1) method is the simplest way to get the previous day in C#. You can use it with DateTime.Today for date-only operations or DateTime.Now to include time, and format the output as needed using ToString() with format specifiers.

Updated on: 2026-03-17T07:04:35+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements