为什么没有DateTime.AddWeeks(),如何在52周前获取DateTime对象? [英] Why is there no DateTime.AddWeeks(), and how can I get a DateTime object for 52 weeks ago?

查看:114
本文介绍了为什么没有DateTime.AddWeeks(),如何在52周前获取DateTime对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.DateTime 对象具有用于 AddYears(),AddMonths(),AddDays(),AddSeconds()等。

我注意到没有 AddWeeks()。为什么?

I've noticed that there is no AddWeeks(). Why is this?

此外,我的要求是获取52周前的价格值。我知道这相当于1年,但具体时间约为52周。

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.

我会做同样的事情吗?

yearOldPrice = _priceService.GetPriceForDate(price.Date.AddYears(-1));

as

yearOldPrice = _priceService.GetPriceForDate(price.Date.AddDays(-7 * 52));

我假设 .AddDays(-7 * 52) .AddWeeks(-52)相同,因为一周中有7天。

I ask on the presumption that .AddDays(-7 * 52) is the same as .AddWeeks(-52), 'cause there's 7 days in a week.

推荐答案

正如您在问题中所指出的,与年和月不同,每周总是有整整7天(无论如何,在我的日历上),因此几乎没有当您需要做的是.AddDays(weeks * 7)时,可以通过使用AddWeeks方法获得。虽然您必须质疑当它们具有AddMinutes和AddHours时的逻辑!

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!

如果确实困扰您,您总是可以为.AddWeeks创建扩展方法,但是:

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);
    }
}

正如其他人指出的那样,一年不是52周。

And as others have pointed out, a year is not 52 weeks.

这篇关于为什么没有DateTime.AddWeeks(),如何在52周前获取DateTime对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆