[SOLVED] How to get yesterday's date in C#

Issue

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

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}

Answered By – Habib

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *