如何获得一周开始的日期时间?

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

喜欢的东西:

DateTime.Now.StartWeek(Monday);
353871 次浏览

这将给你前一个星期天(我想):

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

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

这可能有点黑,但你可以将. dayofweek属性转换为int(它是一个枚举,因为它的底层数据类型没有改变,它默认为int),并使用它来确定一周的前一周。

它显示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);

前一个星期天的代码更简单,因为我们不需要做这样的调整:-

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

使用扩展方法:

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

可以这样使用:

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

稍微啰嗦一点,了解一下文化:

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;

这将是一周的第一个周日的午夜:

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

这就给了你午夜的第一个星期一:

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

你可以使用优秀的伞图书馆:

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

然而,它们似乎已经将星期一存储为一周的第一天(请参阅属性nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn),因此先前的本地化解决方案要好一些。不幸的。

编辑:仔细看看这个问题,似乎Umbrella也可以解决这个问题:

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

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

让我们结合文化安全答案和扩展方法答案:

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

使用# EYZ0:

var monday = DateTime.Now.Previous(DayOfWeek.Monday);
var sunday = DateTime.Now.Previous(DayOfWeek.Sunday);
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;
}

谢谢你的例子。我需要总是使用“CurrentCulture”一周的第一天,对于一个数组,我需要知道确切的天数。这里是我的第一个扩展:

public static class DateTimeExtensions
{
//http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week
//http://stackoverflow.com/questions/1788508/calculate-date-with-monday-as-dayofweek1
public static DateTime StartOfWeek(this DateTime dt)
{
//difference in days
int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.


//As a result we need to have day 0,1,2,3,4,5,6
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}


public static int DayNoOfWeek(this DateTime dt)
{
//difference in days
int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.


//As a result we need to have day 0,1,2,3,4,5,6
if (diff < 0)
{
diff += 7;
}
return diff + 1; //Make it 1..7
}
}

这将返回一周的开始和结束日期:

    private string[] GetWeekRange(DateTime dateToCheck)
{
string[] result = new string[2];
TimeSpan duration = new TimeSpan(0, 0, 0, 0); //One day
DateTime dateRangeBegin = dateToCheck;
DateTime dateRangeEnd = DateTime.Today.Add(duration);


dateRangeBegin = dateToCheck.AddDays(-(int)dateToCheck.DayOfWeek);
dateRangeEnd = dateToCheck.AddDays(6 - (int)dateToCheck.DayOfWeek);


result[0] = dateRangeBegin.Date.ToString();
result[1] = dateRangeEnd.Date.ToString();
return result;


}
我已经在我的博客上发布了计算一周、月、季度和年的开始/结束的完整代码 # EYZ0 < / p >

虽然很丑,但至少还能说出正确的日期

由系统设置一周开始:

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

没有:

    public static DateTime FirstDateInWeek(this DateTime dt, DayOfWeek weekStartDay)
{
while (dt.DayOfWeek != weekStartDay)
dt = dt.AddDays(-1);
return dt;
}

在c#中试试这个。使用这段代码,您可以获得给定一周的第一个日期和最后一个日期。在这里,周日是第一天,周六是最后一天,但您可以根据您的文化设置这两天。

DateTime firstDate = GetFirstDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Sunday);
DateTime lastDate = GetLastDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Saturday);


public static DateTime GetFirstDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
{
DateTime firstDayInWeek = dayInWeek.Date;
while (firstDayInWeek.DayOfWeek != firstDay)
firstDayInWeek = firstDayInWeek.AddDays(-1);


return firstDayInWeek;
}


public static DateTime GetLastDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
{
DateTime lastDayInWeek = dayInWeek.Date;
while (lastDayInWeek.DayOfWeek != firstDay)
lastDayInWeek = lastDayInWeek.AddDays(1);


return lastDayInWeek;
}

把这些都放在一起,加上全球化并允许指定一周的第一天作为我们通话的一部分

public static DateTime StartOfWeek ( this DateTime dt, DayOfWeek? firstDayOfWeek )
{
DayOfWeek fdow;


if ( firstDayOfWeek.HasValue  )
{
fdow = firstDayOfWeek.Value;
}
else
{
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
fdow = ci.DateTimeFormat.FirstDayOfWeek;
}


int diff = dt.DayOfWeek - fdow;


if ( diff < 0 )
{
diff += 7;
}


return dt.AddDays( -1 * diff ).Date;


}

我能想到的最快方法是:

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

这里有一个正确的解决方案。无论一周的第一天是周一、周日还是其他日期,下面的代码都能正常工作。

public static class DateTimeExtension
{
public static DateTime GetFirstDayOfThisWeek(this DateTime d)
{
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
var first = (int)ci.DateTimeFormat.FirstDayOfWeek;
var current = (int)d.DayOfWeek;


var result = first <= current ?
d.AddDays(-1 * (current - first)) :
d.AddDays(first - current - 7);


return result;
}
}


class Program
{
static void Main()
{
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine("Current culture set to en-US");
RunTests();
Console.WriteLine();
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("da-DK");
Console.WriteLine("Current culture set to da-DK");
RunTests();
Console.ReadLine();
}


static void RunTests()
{
Console.WriteLine("Today {1}: {0}", DateTime.Today.Date.GetFirstDayOfThisWeek(), DateTime.Today.Date.ToString("yyyy-MM-dd"));
Console.WriteLine("Saturday 2013-03-02: {0}", new DateTime(2013, 3, 2).GetFirstDayOfThisWeek());
Console.WriteLine("Sunday 2013-03-03: {0}", new DateTime(2013, 3, 3).GetFirstDayOfThisWeek());
Console.WriteLine("Monday 2013-03-04: {0}", new DateTime(2013, 3, 4).GetFirstDayOfThisWeek());
}
}
var now = System.DateTime.Now;


var result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;
    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();
}
}
}
   d = DateTime.Now;
int dayofweek =(int) d.DayOfWeek;
if (dayofweek != 0)
{
d = d.AddDays(1 - dayofweek);
}
else { d = d.AddDays(-6); }
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();
}
}
}
c#中的模数对-1 mod 7工作不好(它应该是6,但c#返回-1) 所以…一个“one-liner"这个问题的解决方案是这样的:)

private static DateTime GetFirstDayOfWeek(DateTime date)
{
return date.AddDays(
-(((int)date.DayOfWeek - 1) -
(int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));
}

我尝试了几次,但我没有解决从星期一开始的一周的问题,导致我的下一个星期一是星期天。所以我对它做了一些修改,让它与下面的代码一起工作:

int delta = DayOfWeek.Monday - DateTime.Now.DayOfWeek;
DateTime monday = DateTime.Now.AddDays(delta == 1 ? -6 : delta);
return monday;

周末也一样(样式为编译这是答案):

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

以下是一些答案的组合。它使用一个扩展方法,允许传入区域性。如果没有传入,则使用当前区域性。这将为它提供最大的灵活性和重用性。

/// <summary>
/// Gets the date of the first day of the week for the date.
/// </summary>
/// <param name="date">The date to be used</param>
/// <param name="cultureInfo">If none is provided, the current culture is used</param>
/// <returns>The date of the beggining of the week based on the culture specifed</returns>
public static DateTime StartOfWeek(this DateTime date, CultureInfo cultureInfo=null) =>
date.AddDays(-1 * (7 + (date.DayOfWeek - (cultureInfo ?? CultureInfo.CurrentCulture).DateTimeFormat.FirstDayOfWeek)) % 7).Date;

使用示例:

public static void TestFirstDayOfWeekExtension() {
DateTime date = DateTime.Now;
foreach(System.Globalization.CultureInfo culture in CultureInfo.GetCultures(CultureTypes.UserCustomCulture | CultureTypes.SpecificCultures)) {
Console.WriteLine($"{culture.EnglishName}: {date.ToShortDateString()} First Day of week: {date.StartOfWeek(culture).ToShortDateString()}");
}
}

如果您需要周六、周日或一周中的任何一天,但不超过当前一周(周六-日),我用这段代码为您提供了支持。

public static DateTime GetDateInCurrentWeek(this DateTime date, DayOfWeek day)
{
var temp = date;
var limit = (int)date.DayOfWeek;
var returnDate = DateTime.MinValue;


if (date.DayOfWeek == day)
return date;


for (int i = limit; i < 6; i++)
{
temp = temp.AddDays(1);


if (day == temp.DayOfWeek)
{
returnDate = temp;
break;
}
}
if (returnDate == DateTime.MinValue)
{
for (int i = limit; i > -1; i++)
{
date = date.AddDays(-1);


if (day == date.DayOfWeek)
{
returnDate = date;
break;
}
}
}
return returnDate;
}

周一

DateTime startAtMonday = DateTime.Now.AddDays(DayOfWeek.Monday - DateTime.Now.DayOfWeek);

在周日

DateTime startAtSunday = DateTime.Now.AddDays(DayOfWeek.Sunday- DateTime.Now.DayOfWeek);

我们喜欢简单的语句:获取当前文化中每周的第一天与当前日期之间的差值,然后从当前日期减去天数:

var weekStartDate = DateTime.Now.AddDays(-((int)now.DayOfWeek - (int)DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek));

步骤1:

创建静态类

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


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

第二步:使用这个类来确定一周的开始和结束日期

DateTime dt = TIMEE.StartOfWeek(DateTime.Now ,DayOfWeek.Monday);
DateTime dt1 = TIMEE.EndOfWeek(DateTime.Now, DayOfWeek.Sunday);

编译这个答案开始,使用以下方法获取一周中任何一天的日期:

public static DateTime GetDayOfWeek(DateTime dateTime, DayOfWeek dayOfWeek)
{
var monday = dateTime.Date.AddDays((7 + (dateTime.DayOfWeek - DayOfWeek.Monday) % 7) * -1);


var diff = dayOfWeek - DayOfWeek.Monday;


if (diff == -1)
{
diff = 6;
}


return monday.AddDays(diff);
}

尝试创建一个使用递归的函数。您的DateTime对象是一个输入,函数返回一个新的DateTime对象,它代表一周的开始。

    DateTime WeekBeginning(DateTime input)
{
do
{
if (input.DayOfWeek.ToString() == "Monday")
return input;
else
return WeekBeginning(input.AddDays(-1));
} while (input.DayOfWeek.ToString() == "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 DateTime GetStartOfWeekDate()
{
// Get today's date
DateTime today = DateTime.Today;
// Get the value for today. DayOfWeek is an enum with 0 being Sunday, 1 Monday, etc
var todayDayOfWeek = (int)today.DayOfWeek;


var dateStartOfWeek = today;
// If today is not Monday, then get the date for Monday
if (todayDayOfWeek != 1)
{
// How many days to get back to Monday from today
var daysToStartOfWeek = (todayDayOfWeek - 1);
// Subtract from today's date the number of days to get to Monday
dateStartOfWeek = today.AddDays(-daysToStartOfWeek);
}


return dateStartOfWeek;


}

我是这样做的:

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

我和很多学校都有合作,所以正确使用周一作为一周的第一天在这里很重要。

这里很多最简洁的答案在周日都不起作用——我们经常在周日返回明天的日期,这不利于运行关于上周活动的报告。

这是我的解决方案,上周一周日,今天周一。

// 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”;所以它是单元可测试的!!