我如何在c#中找到一周的开始(包括周日和周一),只知道当前时间?
喜欢的东西:
DateTime.Now.StartWeek(Monday);
我如何在c#中找到一周的开始(包括周日和周一),只知道当前时间?
喜欢的东西:
DateTime.Now.StartWeek(Monday);
当前回答
c#中的模数对-1 mod 7(它应该是6,但c#返回-1)效果很差 所以…一个“一行程序”的解决方案是这样的:
private static DateTime GetFirstDayOfWeek(DateTime date)
{
return date.AddDays(
-(((int)date.DayOfWeek - 1) -
(int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));
}
其他回答
这可能有点黑,但你可以将. dayofweek属性转换为int(它是一个枚举,因为它的底层数据类型没有改变,它默认为int),并使用它来确定一周的前一周。
它显示DayOfWeek枚举中指定的周从周日开始,因此如果将这个值减去1,就等于周一离当前日期有多少天。我们还需要将周日(0)映射为7,因此给定1 - 7 = -6,周日将映射到前一个周一:-
DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;
DateTime startOfWeek = now.AddDays(1 - (int)now.DayOfWeek);
前一个星期天的代码更简单,因为我们不需要做这样的调整:-
DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
DateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek);
把这些都放在一起,加上全球化并允许指定一周的第一天作为我们通话的一部分
public static DateTime StartOfWeek ( this DateTime dt, DayOfWeek? firstDayOfWeek )
{
DayOfWeek fdow;
if ( firstDayOfWeek.HasValue )
{
fdow = firstDayOfWeek.Value;
}
else
{
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
fdow = ci.DateTimeFormat.FirstDayOfWeek;
}
int diff = dt.DayOfWeek - fdow;
if ( diff < 0 )
{
diff += 7;
}
return dt.AddDays( -1 * diff ).Date;
}
下面的方法应该返回所需的DateTime。周日为true,周一为false:
private DateTime getStartOfWeek(bool useSunday)
{
DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
if(!useSunday)
dayOfWeek--;
if(dayOfWeek < 0)
{// day of week is Sunday and we want to use Monday as the start of the week
// Sunday is now the seventh day of the week
dayOfWeek = 6;
}
return now.AddDays(-1 * (double)dayOfWeek);
}
我尝试了几次,但我没有解决从星期一开始的一周的问题,导致我的下一个星期一是星期天。所以我对它做了一些修改,让它与下面的代码一起工作:
int delta = DayOfWeek.Monday - DateTime.Now.DayOfWeek;
DateTime monday = DateTime.Now.AddDays(delta == 1 ? -6 : delta);
return monday;
通过这种方式计算,您可以选择一周中的哪一天表示新一周的开始(在示例中,我选择了星期一)。
请注意,对星期一进行这个计算将得到当前的星期一,而不是以前的星期一。
//Replace with whatever input date you want
DateTime inputDate = DateTime.Now;
//For this example, weeks start on Monday
int startOfWeek = (int)DayOfWeek.Monday;
//Calculate the number of days it has been since the start of the week
int daysSinceStartOfWeek = ((int)inputDate.DayOfWeek + 7 - startOfWeek) % 7;
DateTime previousStartOfWeek = inputDate.AddDays(-daysSinceStartOfWeek);