How to perform multiplication in date (datetimeoffset format)

I have following 3 fields startingdate, expirydate, number of months

startingdate = DateTimeOffset.Now;

and number of months, say 24 months

How to calculate expirydate = ?

Can anybody give me an idea?

Jon Skeet
people
quotationmark

You don't need multiplication in this case - just addition, specifying the units:

DateTimeOffset startDate = DateTimeOffset.Now;
DateTimeOffset expiryDate = startDate.AddMonths(months);

Two things to note:

  • Date and time arithmetic can be odd. In your example case it's less likely to be odd than normal, as you've got 2 years, so the only corner case is adding 2 years to February 29th and getting February 28th; normally you'd need to consider (say) adding 1 month to August 31st and getting September 30th. In other words, just because two expiry dates are the same doesn't mean they came from the same start date.
  • You might want to consider using DateTimeOffset.UtcNow and doing everything in UTC, rather than using the local time zone. Using DateTimeOffset instead of DateTime protects you from time zone problems to some extent, but keeping everything in UTC is clearer.
  • If you really mean you have dates rather than dates and times, you might want to explicitly use midnight... it's unfortunate that .NET doesn't have any "date-only" type. You might want to consider using my Noda Time which is designed to make things rather clearer than the BCL API.

people

See more on this question at Stackoverflow