Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get yesterday's date in C#

Tags:

c#

asp.net

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?

like image 247
akhil Avatar asked Jun 29 '12 05:06

akhil


People also ask

How to get previous date in c?

To get previous day's date we are using a user define function getYesterdayDate() which has date structure as pointer, any changes made in the structure date inside this function will reflect to the actual values in the main().

How do I find yesterday's date?

How do you get yesterdays' date using JavaScript? We use the setDate() method on yesterday , passing as parameter the current day minus one. Even if it's day 1 of the month, JavaScript is logical enough and it will point to the last day of the previous month.


2 Answers

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}

like image 98
Habib Avatar answered Oct 11 '22 14:10

Habib


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"); 
like image 27
Mark Byers Avatar answered Oct 11 '22 13:10

Mark Byers