I want to set a DateTime property to previous day at 00:00:00. I don\'t know why DateTime.AddDays(-1) isn\'t working. Or why DateTime.AddTicks(-1) isn\'t working. First sho
DateTime is an immutable struct. When you call AddDays() or AddTicks()
it returns a new instance of a DateTime, it does NOT modify the instance you called it on. Make sure you assign the result to a variable or there is no visible change in your code:
DateTime d1 = DateTime.Now;
d1 = d1.AddDays(-1); // assign back to see the new instance
If you need to reset the time portion of the date to midnight, you will need to use an explicit constructor call:
DateTime d1 = DateTime.Now;
DateTime d2 = new DateTime( d1.Year, d1.Month, d1.Day, 0, 0, 0 );
DateTime d3 = d1.Date; // a simpler alternative to the above...
DateTime newDate= new DateTime();
var LastDay2 = newDate.AddMonths(1);
var LastDay3 = LastDay2.Day * (-1);
var d5 = LastDay2.AddDays(LastDay3);
Maybe your problem is AddDays
doesn't modify the object, it returns an DateTime with the changed days. So it should be:
DateTime Yesterday = CurrentDay.AddDays(-1);
Have you tried this:
var yesterday = System.DateTime.Now.Date.Subtract(new TimeSpan(1, 0, 0, 0))
the easiest way is this..
DateTime yesterday = DateTime.Now.Date.AddDays(-1);
now if you are trying to use a variable that has already been created, you would do this...
DateTime yesterday = DateTime.Now; // will give you today's date
yesterday = yesterday.Date.AddDays(-1); // will give you yesterday's date at 12:00 AM
Possibly posting your code will show us what you are doing wrong.
Try:
<DateTime>.Date.AddDays(-1);
This will strip off the time and give you midnight the previous day.
EDIT: Yes sorry, I meant to put some sort of indication that "DateTime" meant the variable in question. I added brackets around it.