How to print yesterday's date in C#

C sharp program to print yesterday’s date:

In this post, we will learn how to print yesterday’s date in C#. I will show you two different ways to do that.

Method 1: By using DateTime:

We can use the DateTime struct to get the current date and we can use it to get yesterday’s date.

Below is the complete program:

using System;
					
public class Program
{
	public static void Main()
	{
		var today = DateTime.Today;
		var yesterDay = today.AddDays(-1);
		
		Console.WriteLine("Yesterday "+yesterDay.ToString());
	}
}

In this program, DateTime.Today gives us the current date-time. We are using AddDays to subtract one day from this. We are passing -1 to subtract the day.

The last line is printing yesterday’s date-time.

It will print the date-time of yesterday as like below:

Yesterday 8/29/2021 12:00:00 AM

Formatting the result:

We can also pass one formatter string to format the result. For example:

using System;
					
public class Program
{
	public static void Main()
	{
		var today = DateTime.Today;
		var yesterDay = today.AddDays(-1);
		
		Console.WriteLine("Yesterday "+yesterDay.ToString("dd-MM-yyyy"));
	}
}

It will print:

Yesterday 29-08-2021

Printing the day:

We can also print the day in string. We need to read the property DayOfWeek for that.

using System;
					
public class Program
{
	public static void Main()
	{
		var today = DateTime.Today;
		var yesterDay = today.AddDays(-1);
		
		Console.WriteLine("Yesterday "+yesterDay.DayOfWeek.ToString());
	}
}

It will print the day as like below:

Yesterday Sunday

Method 2: By using TimeSpan:

We can create one TimeSpan object that can be subtracted from the current date object.

using System;
					
public class Program
{
	public static void Main()
	{
		var today = DateTime.Today;
		var oneDay = new TimeSpan(1, 0, 0, 0);
		
		var yesterDay = today - oneDay;
		
		Console.WriteLine("Yesterday "+yesterDay.ToString());
	}
}

It will print one similar output as the above examples.

You might also like: