The System.DateTime
object has methods to AddYears(), AddMonths(), AddDays(), AddSeconds()
, etc.
I've noticed that there is no AddWeeks()
. Why is this?
Also, my requirement is to get a price value from 52 weeks ago. I know this equates to 1 year, but they were specific about 52 weeks.
Would it be the same for me to do:
yearOldPrice = _priceService.GetPriceForDate(price.Date.AddYears(-1));
as
yearOldPrice = _priceService.GetPriceForDate(price.Date.AddDays(-7 * 52));
I ask on the presumption that .AddDays(-7 * 52)
is the same as .AddWeeks(-52)
, 'cause there's 7 days in a week.
As you've noted in your question, unlike Years and Months, there are always exactly 7 days per week (on my calendar, anyway), so there's very little to be gained by having an AddWeeks method when all you need to do is .AddDays(weeks * 7). Though you have to question the logic when they have AddMinutes and AddHours! Damn them and their inconsistencies!
You could always create an extension method for .AddWeeks if it really bothers you, though:
public static class DateTimeExtensions
{
public static DateTime AddWeeks(this DateTime dateTime, int numberOfWeeks)
{
return dateTime.AddDays(numberOfWeeks * 7);
}
}
And as others have pointed out, a year is not 52 weeks.
The abstract Calendar
class implements the method you're after, you can either use your locale's calendar, or create an object of a class that implements it:
DateTime dt = CultureInfo.InvariantCulture.Calendar.AddWeeks(datetime, weeks);
GregorianCalendar gc = new GregorianCalendar();
DateTime dt = gc.AddWeeks(datetime, weeks);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With