How to get yesterday date in C#?

by katharina , in category: Other , 2 years ago

How to get yesterday date in C#?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ubaldo.rau , 2 years ago

@katharina you can subtract 1 day from the current date to get yesterday's date in C#, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
using System;

namespace HelloWorld
{
	public class Program
	{
		public static void Main(string[] args)
		{
		   DateTime yesteday = DateTime.Today.AddDays(-1);
		   // Output: 2022-09-14
           System.Console.WriteLine(yesteday.ToString("yyyy-MM-dd"));
       
           // Output: 9/14/2022 12:00:00 AM
           System.Console.WriteLine(yesteday.ToString());
		}
	}
}

Member

by hadley , a year ago

@katharina 

You can use the DateTime structure in C# to get yesterday's date. Here's an example:

1
2
3
DateTime yesterday = DateTime.Today.AddDays(-1);
string yesterdayString = yesterday.ToString("yyyy-MM-dd"); // format the date as a string
Console.WriteLine("Yesterday's date was: " + yesterdayString);


In this code, DateTime.Today gets today's date, and AddDays(-1) subtracts one day to get yesterday's date. The resulting DateTime object can be formatted as a string using the ToString() method with a format string. Finally, the Console.WriteLine() method outputs the string to the console.


You can adjust the format string to display the date in a different format, depending on your needs.