C# 获取一周的第一个星期一的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1665832/
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
Get date of first Monday of the week?
提问by Lasse Edsvik
I was wondering if you guys know how to get the date of currents week's monday based on todays date?
我想知道你们是否知道如何根据今天的日期获得当前周星期一的日期?
i.e 2009-11-03 passed in and 2009-11-02 gets returned back
即 2009-11-03 传入,2009-11-02 返回
/M
/M
采纳答案by Pondidum
This is what i use (probably not internationalised):
这就是我使用的(可能不是国际化的):
DateTime input = //...
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime monday = input.AddDays(delta);
回答by PaulB
Something like this would work
像这样的东西会起作用
DateTime dt = DateTime.Now;
while(dt.DayOfWeek != DayOfWeek.Monday) dt = dt.AddDays(-1);
I'm sure there is a nicer way tho :)
我相信有更好的方法 :)
回答by Konamiman
Try this:
尝试这个:
public DateTime FirstDayOfWeek(DateTime date)
{
var candidateDate=date;
while(candidateDate.DayOfWeek!=DayOfWeek.Monday) {
candidateDate=candidateDate.AddDays(-1);
}
return candidateDate;
}
EDITfor completeness: overload for today's date:
编辑完整性:今天日期的过载:
public DateTime FirstDayOfCurrentWeek()
{
return FirstDayOfWeek(DateTime.Today);
}
回答by Marco
The Pondium answer can search Forward in some case. If you want only Backward search I think it should be:
在某些情况下,Pondium 答案可以搜索 Forward。如果你只想要向后搜索,我认为它应该是:
DateTime input = //...
int delta = DayOfWeek.Monday - input.DayOfWeek;
if(delta > 0)
delta -= 7;
DateTime monday = input.AddDays(delta);
回答by HelloWorld
var now = System.DateTime.Now;
var result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;
Probably will return you with Monday. Unless you are using a culture where Monday is not the first day of the week.
可能会在星期一回来。除非您使用的文化是星期一不是一周的第一天。
回答by Gh61
What about:
关于什么:
CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek
Why don't use native solution?
为什么不使用本机解决方案?
回答by Donskikh Andrei
public static class DateTimeExtension
{
public static DateTime GetFirstDayOfWeek(this DateTime date)
{
var firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
while (date.DayOfWeek != firstDayOfWeek)
{
date = date.AddDays(-1);
}
return date;
}
}
International here. I think as extension it can be more useful.
国际在这里。我认为作为扩展它可以更有用。