calendar获取本周一的日期_获取本周的第一天和最后一天的日期知道周数

I need to get the date of the first and last day of the week knowing the week number.

I get a start date and an end date, representing the first and last day of a selected week in a given year. then I need to get the start date and end date of the same week of the previous year to do a graphical comparison of some data.

I managed to get the week number based on the given start date and end date. Now I need to get the date of the first day and last day of the same week of the previous year. How could I do this quickest ?

EDIT: This is how I got the week number:

private int GetWeekNumber(DateTime date)

{

GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);

return calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);

}

解决方案

You can use following two methods to calculate the week-number and the start-date of a given weeknumber according to a given year:

// this method is borrowed from http://stackoverflow.com/a/11155102/284240

public static int GetIso8601WeekOfYear(DateTime time)

{

DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);

if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)

{

time = time.AddDays(3);

}

return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

}

public static DateTime FirstDateOfWeek(int year, int weekOfYear, System.Globalization.CultureInfo ci)

{

DateTime jan1 = new DateTime(year, 1, 1);

int daysOffset = (int)ci.DateTimeFormat.FirstDayOfWeek - (int)jan1.DayOfWeek;

DateTime firstWeekDay = jan1.AddDays(daysOffset);

int firstWeek = ci.Calendar.GetWeekOfYear(jan1, ci.DateTimeFormat.CalendarWeekRule, ci.DateTimeFormat.FirstDayOfWeek);

if ((firstWeek <= 1 || firstWeek >= 52) && daysOffset >= -3)

{

weekOfYear -= 1;

}

return firstWeekDay.AddDays(weekOfYear * 7);

}

Then you can get both dates in the following way:

// 46

int thisWeekNumber = GetIso8601WeekOfYear(DateTime.Today);

// 11/11/2013

DateTime firstDayOfWeek= FirstDateOfWeek(2013, thisWeekNumber, CultureInfo.CurrentCulture);

// 11/12/2012

DateTime firstDayOfLastYearWeek = FirstDateOfWeek(2012, thisWeekNumber, CultureInfo.CurrentCulture);

Add 6 days to get the end of the week.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值