Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no DateTime.AddWeeks(), and how can I get a DateTime object for 52 weeks ago?

Tags:

c#

datetime

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.

like image 623
DaveDev Avatar asked Jul 27 '11 15:07

DaveDev


2 Answers

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.

like image 105
Steve Morgan Avatar answered Sep 30 '22 19:09

Steve Morgan


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);
like image 21
Jamie Kitson Avatar answered Sep 30 '22 20:09

Jamie Kitson