astroboy
astroboy

Reputation: 59

How to subtract a year and a day from the datetime?

I see the answer like this but how to add 1 day after this? Like 2 years ago and 1 day.

var myDate = DateTime.Now;
var newDate = myDate.AddYears(-2);
var NewExpiryDate = myDate.AddDays(-1);
var NewFinalDate = ?

Upvotes: 1

Views: 343

Answers (1)

sujith karivelil
sujith karivelil

Reputation: 29006

What you are doing wrong:

myDate will be the current date then you add -2 years with the current date and assign to newDate. Which will not update the myDate it's still the current date, so you need to add -1 days to the newDate to get the required output. A more simple way you can use like this:

var newDate = myDate.AddYears(-2).AddDays(-1);

Note : The date Functions .AddYears() will not alter the source, it will return a new DateTime that adds the specified number of years to the value of this instance. As Soner said, DateTime is an immutable type Which means is an object whose state cannot be modified after it is created.

Upvotes: 7

Related Questions