[c#] how to get yesterday's date in C#

I want to retrieve yesterday's date in my ASP.NET web application using C#.

I already digged about the topic but I guess I m not able to understand it.

Code i m using is just giving me todays 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 do so?

Thanks in Advance :)

This question is related to c# asp.net

The answer is

DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);

There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.

Also you can have a desirable format in the .ToString() version of the DateTime instance

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

You will get yesterday date by this following code snippet.

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

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");

Something like this should work

var yesterday = DateTime.Now.Date.AddDays(-1);

DateTime.Now gives you the current date and time.

If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.

Finally .AddDays(-1) removes 1 day to give you yesterday.

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");


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

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

DateTime dateTime = DateTime.Now ; 
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");

The above snippet will work. It is also advisable to make single instance of DateTime.Now;