C# 如何获得本周开始的日期时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 09:45:12  来源:igfitidea点击:

How can I get the DateTime for the start of the week?

提问by GateKiller

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

我如何在 C# 中只知道当前时间找到一周的开始(周日和周一)?

Something like:

就像是:

DateTime.Now.StartWeek(Monday);

采纳答案by Compile This

Use an extension method. They're the answer to everything, you know! ;)

使用扩展方法。他们是一切的答案,你知道!;)

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        return dt.AddDays(-1 * diff).Date;
    }
}

Which can be used as follows:

可以按如下方式使用:

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);

回答by Skizz

This would give you the preceding Sunday (I think):

这会给你前一个星期天(我认为):

DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);

回答by firedfly

The following method should return the DateTime that you want. Pass in true for Sunday being the first day of the week, false for Monday:

以下方法应返回所需的 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);
}

回答by ljs

This may be a bit of a hack, but you can cast the .DayOfWeek property to an int (it's an enum and since its not had its underlying data type changed it defaults to int) and use that to determine the previous start of the week.

这可能有点麻烦,但您可以将 .DayOfWeek 属性转换为 int(它是一个枚举,并且由于其底层数据类型没有更改,因此默认为 int)并使用它来确定一周的前一个开始.

It appears the week specified in the DayOfWeek enum starts on Sunday, so if we subtract 1 from this value that'll be equal to how many days the Monday is before the current date. We also need to map the Sunday (0) to equal 7 so given 1 - 7 = -6 the Sunday will map to the previous Monday:-

看起来 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);

The code for the previous Sunday is simpler as we don't have to make this adjustment:-

上周日的代码更简单,因为我们不必进行此调整:-

DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
DateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek);

回答by Jason Navarrete

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;

回答by Glenn Slaven

This would give you midnight on the first Sunday of the week:

这会给你一周的第一个星期天的午夜:

DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek, t.Hour, t.Minute, t.Second);

This gives you the first Monday at midnight:

这为您提供了第一个星期一的午夜:

DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek - 1, t.Hour, t.Minute, t.Second);

回答by Domenic

You could use the excellent Umbrella library:

您可以使用优秀的Umbrella 库

using nVentive.Umbrella.Extensions.Calendar;
DateTime beginning = DateTime.Now.BeginningOfWeek();

However, they doseem to have stored Monday as the first day of the week (see the property nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn), so that previous localized solution is a bit better. Unfortunate.

但是,他们似乎确实将星期一存储为一周的第一天(请参阅属性nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn),因此以前的本地化解决方案要好一些。不幸的。

Edit: looking closer at the question, it looks like Umbrella might actually work for that too:

编辑:仔细观察这个问题,看起来 Umbrella 也可能真的适用于这个问题:

// Or DateTime.Now.PreviousDay(DayOfWeek.Monday)
DateTime monday = DateTime.Now.PreviousMonday(); 
DateTime sunday = DateTime.Now.PreviousSunday();

Although it's worth noting that if you ask for the previous Monday on a Monday, it'll give you seven days back. But this is also true if you use BeginningOfWeek, which seems like a bug :(.

尽管值得注意的是,如果您在星期一要求前一个星期一,它会给您 7 天。但是,如果您使用BeginningOfWeek,这也是正确的,这似乎是一个错误 :(。

回答by Joel Coehoorn

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));
    }
}

回答by Simon

Using Fluent DateTime:

使用流畅的日期时间

var monday = DateTime.Now.Previous(DayOfWeek.Monday);
var sunday = DateTime.Now.Previous(DayOfWeek.Sunday);

回答by mails2008

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;
}