How can I get the DateTime for the start of the we

2018-12-31 17:32发布

How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?

Something like:

DateTime.Now.StartWeek(Monday);

标签: c# datetime
28条回答
孤独寂梦人
2楼-- · 2018-12-31 18:02

Let's combine the culture-safe answer and the extension method answer:

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));
    }
}
查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 18:04
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;
}
查看更多
一个人的天荒地老
4楼-- · 2018-12-31 18:05

A little more verbose and culture-aware:

System.Globalization.CultureInfo ci = 
    System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
DayOfWeek today = DateTime.Now.DayOfWeek;
DateTime sow = DateTime.Now.AddDays(-(today - fdow)).Date;
查看更多
忆尘夕之涩
5楼-- · 2018-12-31 18:05

Quickest way I can come up with is:

var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);

If you would like any other day of the week to be your start date all you need to do is add the DayOfWeek value to the end

var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);

var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);
查看更多
泪湿衣
6楼-- · 2018-12-31 18:05

Ugly but it at least gives the right dates back

With start of week set by system:

    public static DateTime FirstDateInWeek(this DateTime dt)
    {
        while (dt.DayOfWeek != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
            dt = dt.AddDays(-1);
        return dt;
    }

Without:

    public static DateTime FirstDateInWeek(this DateTime dt, DayOfWeek weekStartDay)
    {
        while (dt.DayOfWeek != weekStartDay)
            dt = dt.AddDays(-1);
        return dt;
    }
查看更多
临风纵饮
7楼-- · 2018-12-31 18:05

Same for end of week (in style of @Compile This's answer):

    public static DateTime EndOfWeek(this DateTime dt)
    {
        int diff = 7 - (int)dt.DayOfWeek;

        diff = diff == 7 ? 0 : diff;

        DateTime eow = dt.AddDays(diff).Date;

        return new DateTime(eow.Year, eow.Month, eow.Day, 23, 59, 59, 999) { };
    }
查看更多
登录 后发表回答