假设我的输入为March 31, 2015
我怎样才能获得March 31, 2015
所在的一周中的日子?
在这种情况下,它应输出:
March 29, 2015
- April 4, 2015
我找到了类似here的内容,但它并不是我所寻找的东西,因为我输入的是一个日期本身。
答案 0 :(得分:7)
DateTime date = new DateTime(2015, 3, 31);
DateTime weekFirstDay = date.AddDays(DayOfWeek.Sunday - date.DayOfWeek);
DateTime weekLastDay = weekFirstDay.AddDays(6);
答案 1 :(得分:3)
以下是一种从给定的DateTime
周开始:
public static DateTime GetWeekStartDate(DateTime value)
{
return value.AddDays(-(int)value.DayOfWeek).Date;
}
周末:
public static DateTime GetWeekEndDate(DateTime value)
{
return value.AddDays(6 - (int)value.DayOfWeek).Date;
}
答案 2 :(得分:2)
DayOfWeek firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
DateTime startDate = DateTime.Now;
while (firstDayOfWeek != startDate.DayOfWeek)
{
startDate = startDate.AddDays(-1);
}
DateTime firstDay = startDate.Date;
DateTime lastDay = startDate.AddDays(6);