[英]Get same day of same week in last year
I was looking for a way to fetch the same day of the current week as a year ago.我一直在寻找一种方法来获取与一年前相同的一周中的一天。 For example, today is:
例如,今天是:
Assume this is the check-in date, the check-out date I expect to get is:假设这是入住日期,我希望得到的退房日期是:
Because it's the same day (Wednesday) as last year.因为和去年是同一天(星期三)。 But I need to take leap years into account, so I need to see if the current year is a leap year and if it is, if it has passed the 29th of February, the same with the date last year.
但是我需要考虑闰年,所以我需要看看今年是否是闰年,如果是,是否已经过了 2 月 29 日,与去年的日期相同。
How to do this using .net core?如何使用 .net 内核执行此操作? I thought of something like:
我想到了类似的东西:
private DateTime GetDayOneYearBefore()
{
if(DateTime.IsLeapYear(DateTime.Today.Year) && DateTime.Today.Month > 2){
return DateTime.Today.AddDays(-365);
}
else if(DateTime.IsLeapYear(DateTime.Today.Year) && DateTime.Today.Month <= 2){
return DateTime.Today.AddDays(-364);
}
}
Since you mention the "same week" I suppose you want to get the same day of the week in the same week number?既然您提到“同一周”,我想您想在同一周数中获得一周中的同一天?
If so, you can do the following:如果是这样,您可以执行以下操作:
// In the System.DayOfWeek enum Sunday = 0, while Monday = 1
// This converts DateTime.DayOfWeek to a range where Monday = 0 and Sunday = 6
static int DayOfWeek(DateTime dt)
{
const int weekStart = (int)System.DayOfWeek.Monday;
const int daysInAWeek = 7;
return (daysInAWeek - (weekStart - (int)dt.DayOfWeek)) % daysInAWeek;
}
var calendar = CultureInfo.CurrentCulture.Calendar;
var weekNum = calendar.GetWeekOfYear(DateTime.Today, CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday);
var todayLastYear = DateTime.Today.AddYears(-1);
var lastYearWeekNum = calendar.GetWeekOfYear(todayLastYear, CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday);
var sameWeekLastYear = todayLastYear.AddDays(7 * (weekNum - lastYearWeekNum));
var sameDaySameWeekLastYear = sameWeekLastYear.AddDays(DayOfWeek(DateTime.Today) - DayOfWeek(sameWeekLastYear));
As you might notice there's a little convertion method, since I normally work with Monday being the first day of the week.您可能会注意到有一种转换方法,因为我通常将星期一作为一周的第一天。 If you prefer a different day to be the first day of the week, simply replace
System.DayOfWeek.Monday
with which ever day you'd like.如果您希望将不同的一天作为一周的第一天,只需将
System.DayOfWeek.Monday
替换为您想要的每一天。
See this fiddle for a test run.请参阅this fiddle进行测试运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.