how to get yesterday's date in C#

I want to retrieve yesterday's date in my ASP.NET web application using C#. I've tried searching for a solution but have not had much success. The code I'm using just outputs today's date:

string yr = DateTime.Today.Year.ToString();
string mn = DateTime.Today.Month.ToString();
string dt = DateTime.Today.Day.ToString();
date = string.Format("{0}-{1}-{2}", yr, mn, dt);

How can I get yesterday's date?


Solution 1:

Use DateTime.AddDays() method with value of -1

var yesterday = DateTime.Today.AddDays(-1);

That will give you : {6/28/2012 12:00:00 AM}

You can also use

DateTime.Now.AddDays(-1)

That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}

Solution 2:

The code you posted is wrong.

You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".

Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.

string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

Solution 3:

You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that

 string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");

OR

 string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

Solution 4:

You will get yesterday date by this following code snippet.

DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);