我如何在c#中找到一周的开始(包括周日和周一),只知道当前时间?
喜欢的东西:
DateTime.Now.StartWeek(Monday);
我如何在c#中找到一周的开始(包括周日和周一),只知道当前时间?
喜欢的东西:
DateTime.Now.StartWeek(Monday);
当前回答
让我们结合文化安全答案和扩展方法答案:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
return DateTime.Today.AddDays(-(DateTime.Today.DayOfWeek- fdow));
}
}
其他回答
我能想到的最快方法是:
var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
如果您希望将一周中的任何一天作为您的开始日期,您所需要做的就是在结束时添加DayOfWeek值
var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);
var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);
下面的方法应该返回所需的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);
}
我们喜欢简单的语句:获取当前文化中每周的第一天与当前日期之间的差值,然后从当前日期减去天数:
var weekStartDate = DateTime.Now.AddDays(-((int)now.DayOfWeek - (int)DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek));
var now = System.DateTime.Now;
var result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;
我是这样做的:
DateTime.Now.Date.AddDays(-(DateTime.Now.Date.DayOfWeek == 0 ? 7 : (int)DateTime.Now.Date.DayOfWeek) + 1)
这段代码所做的就是从给定的日期时间中减去天数。
如果星期几是0(星期日),那么减去7,否则减去星期几。
然后在前一行的结果上加上1天,这将给出该日期的星期一。
这样你就可以在最后摆弄数字(1)来得到你想要的那一天。
private static DateTime GetDay(DateTime date, int daysAmount = 1)
{
return date.Date.AddDays(-(date.Date.DayOfWeek == 0 ? 7 : (int)date.Date.DayOfWeek) + daysAmount);
}
如果你真的想使用DayOfWeek枚举,那么可以使用这样的东西…虽然我个人更喜欢上面的那个,因为我可以增加或减少任何数量的天数。
private static DateTime GetDayOfWeek(DateTime date, DayOfWeek dayOfWeek = DayOfWeek.Monday)
{
return date.Date.AddDays(-(date.Date.DayOfWeek == 0 ? 7 : (int)date.Date.DayOfWeek) + (dayOfWeek == 0 ? 7 : (int)dayOfWeek));
}