How to find yesterdays date

  • Thread starter Thread starter Mike P
  • Start date Start date
M

Mike P

How do I use DateTime to get for example, yesterdays date, or the date 5
days ago? I am using DateTime.Now.ToString() to get today's date, and I
need to also find the date at certain intervals back from that.


Any assistance would be really appreciated.


Cheers,

Mike
 
You can use DateTime.Subtract method.

Five days ago would be:
DateTime date = DateTime.Now.Subtract(new TimeSpan(5, 0, 0, 0));

It's one way... I'm not sure it is the easiest or the best way but it does
work.
 
DateTime today = DateTime.Now;
DateTime yesterday = today.Subtract(new TimeSpan(1, 0, 0, 0));
DateTime fivedaysago = today.Subtract(new TimeSpan(5, 0, 0, 0));

Robert
 
One option is to subtract the TimeSpan as in: DateTime.Now - new TimeSpan(<#
of days back>, 0, 0, 0). Or use the DateTime.Subtract() method.

How do I use DateTime to get for example, yesterdays date, or the date 5
days ago? I am using DateTime.Now.ToString() to get today's date, and I
need to also find the date at certain intervals back from that.


Any assistance would be really appreciated.


Cheers,

Mike
 
Thanks Robert, C,

I now have the problem where I am reading in the date from an XML file
in the format YYYY-MM-DD, and when I convert to DateTime in C#, the day
and month get switched around, so 2004-08-01 becomes 08/01/2004 when I
use Convert.ToDateTime.

Is there a simple way to convert this properly, rather than the messy
way of splitting the string up and building the new string up bit by bit
myself?


Cheers,

lfc77
 
Hi Mike,

You can use DateTime.Parse and specify any format you like in a DateTimeFormatInfo

DateTimeFormatInfo di = new DateTimeFormatInfo();

di.ShortDatePattern = "YYYY-MM-DD";

DateTime dt = DateTime.Parse("2004-08-01", di);
 
Oh yeah, that was all wrong, use this instead

DateTime dt = DateTime.ParseExact("2004-08-01", "yyyy-dd-MM", Thread.CurrentThread.CurrentCulture, DateTimeStyles.NoCurrentDateDefault);

Change CurrentCulture with the culture of your choice, though it shouldn't have any influence.
 
Hi Mike,

Take a look at DateTime.ParseExact , it's what you are looking for :)

Cheers,
 
One of the possible ways is the following:

string today = DateTime.Now.ToString();
string yesterday = DateTime.Today.AddDays(-1).ToString();

listBox1.Items.Add(today);
listBox1.Items.Add(yesterday);
 
Back
Top