我如何在c#中找到一周的开始(包括周日和周一),只知道当前时间?
喜欢的东西:
DateTime.Now.StartWeek(Monday);
我如何在c#中找到一周的开始(包括周日和周一),只知道当前时间?
喜欢的东西:
DateTime.Now.StartWeek(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);
其他回答
让我们结合文化安全答案和扩展方法答案:
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));
}
}
public static System.DateTime getstartweek()
{
System.DateTime dt = System.DateTime.Now;
System.DayOfWeek dmon = System.DayOfWeek.Monday;
int span = dt.DayOfWeek - dmon;
dt = dt.AddDays(-span);
return dt;
}
using System;
using System.Globalization;
namespace MySpace
{
public static class DateTimeExtention
{
// ToDo: Need to provide culturaly neutral versions.
public static DateTime GetStartOfWeek(this DateTime dt)
{
DateTime ndt = dt.Subtract(TimeSpan.FromDays((int)dt.DayOfWeek));
return new DateTime(ndt.Year, ndt.Month, ndt.Day, 0, 0, 0, 0);
}
public static DateTime GetEndOfWeek(this DateTime dt)
{
DateTime ndt = dt.GetStartOfWeek().AddDays(6);
return new DateTime(ndt.Year, ndt.Month, ndt.Day, 23, 59, 59, 999);
}
public static DateTime GetStartOfWeek(this DateTime dt, int year, int week)
{
DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);
return dayInWeek.GetStartOfWeek();
}
public static DateTime GetEndOfWeek(this DateTime dt, int year, int week)
{
DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);
return dayInWeek.GetEndOfWeek();
}
}
}
我和很多学校都有合作,所以正确使用周一作为一周的第一天在这里很重要。
这里很多最简洁的答案在周日都不起作用——我们经常在周日返回明天的日期,这不利于运行关于上周活动的报告。
这是我的解决方案,上周一周日,今天周一。
// Adding 7 so remainder is always positive; Otherwise % returns -1 on Sunday.
var daysToSubtract = (7 + (int)today.DayOfWeek - (int)DayOfWeek.Monday) % 7;
var monday = today
.AddDays(-daysToSubtract)
.Date;
记住为“today”使用一个方法参数,这样它就可以进行单元测试!!
namespace DateTimeExample
{
using System;
public static class DateTimeExtension
{
public static DateTime GetMonday(this DateTime time)
{
if (time.DayOfWeek != DayOfWeek.Monday)
return GetMonday(time.AddDays(-1)); //Recursive call
return time;
}
}
internal class Program
{
private static void Main()
{
Console.WriteLine(DateTime.Now.GetMonday());
Console.ReadLine();
}
}
}