2008-09-01 85 views

回答

568

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

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

編輯:更新的評論使用代碼標記每@JustinStolle 可以簡化這個如下: `INT DIFF =一週中的某天 - dt.DayOfWeek; return dt.AddDays(diff).Date;` – Troy 2011-03-28 23:28:29

+8

特洛伊,如果給定日期是星期日,星期一是星期一,我不相信您的代碼有效。它將返回(星期日+ 1)而不是(星期日 - 6) – 2012-04-23 14:55:04

+1

如果`dt`是UTC並且已經是一週的開始,則這不起作用,例如`2012年9月3日星期一00:00:00`在當地時間是`Mon,2012年9月3日00:00:00'。所以它需要將`dt`轉換爲本地時間或做一些更智能的事情。如果輸入是UTC,它還需要將結果作爲UTC返回。 – row1 2012-09-06 04:12:08

8

這將使你前面的週日(我認爲):

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

下面的方法應該返回所需的日期時間。在真正的通週日是一週的第一天,假星期一:

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

這可能是一個黑客位的,但你可以.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); 

前一個星期天的代碼是簡單,因爲我們不」 t必須進行此調整: -

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

一點更詳細的文化感知:

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; 
+2

得到了一個錯誤:this today = SUNDAY; fdow =星期一; (today - fdow)== -1; DateTime.Now.AddDays( - ( - 1))。Date == DateTime.Now.AddDays(+1).Date; 01-02-2010!= 25-01-2010 !! – balexandre 2010-01-31 22:44:48

+2

如果你在星期天試試這個,那麼它基本上是在爲GB執行AddDays(0 - 1)。所以它需要@Sarcastic的if語句 – 2011-05-15 14:30:29

2

這將會給你的第一個星期日午夜周:

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

這給出y在午夜歐的第一個星期一:

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

你可以使用優秀的Umbrella library

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

然而,他們似乎已經存儲星期一作爲一週的第一天(查看屬性nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn),因此以前的本地化解決方案會更好一些。不幸的。

編輯:看問題更近,它看起來像傘實際上可能也太工作:

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

雖然值得注意的是,如果你問上週一在週一,它我會在七天後給你。但是,如果您使用BeginningOfWeek,這也是如此,這看起來像一個錯誤:(。

14

讓我們結合文化安全的答案,並擴展方法答案:

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

使用Fluent DateTime

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

感謝您的例子。我需要一直使用的一週「的CurrentCulture」第一天爲一個數組,我需要知道確切的Daynumber ..所以這裏是我的第一個擴展:

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

這將返回星期都開始和一週的結束日期:

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; 

    } 

我已經發布計算開始/周,月,季度和年底在我的博客 ZamirsBlog

13

醜陋的完整代碼,但它至少給右邊的日期可以追溯到

隨着本週開始通過系統設置:

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

這種嘗試在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; 
} 
3

全部放在一起,隨着全球化和允許指定一週的第一天作爲呼叫的一部分,我們有

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; 

} 
52

我能想出最快的方法是:

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

似乎沒有人正確尚未有回答了這個。如果有人需要,我會在這裏粘貼我的解決方案。無論一週中的第一天是星期一還是星期日或其他地方,以下代碼都可以工作。

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()); 
    } 
} 
2
var now = System.DateTime.Now; 

var result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date; 
0
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(); 
      } 
     } 
    } 
-1
d = DateTime.Now; 
      int dayofweek =(int) d.DayOfWeek; 
      if (dayofweek != 0) 
      { 
       d = d.AddDays(1 - dayofweek); 
      } 
      else { d = d.AddDays(-6); } 
5
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(); 
     } 
    } 
} 
1

模在C#中的工作壞-1mod7(應該是6,C#返回-1) 所以...... 「oneliner」 解決方案,這將看像這樣:)

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

嘗試了幾個,但沒有解決問題,一個星期一開始,週一,resulti讓我在星期天即將到來的星期一。所以,我修改了一下,得到它與此代碼的工作:

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

同爲周結束(在@Compile這的回答風格):

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

下面是幾個組合的答案。它使用擴展方法,允許文化傳入,如果沒有傳入,則使用當前的文化。這將給它最大的靈活性和重複使用。

/// <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()}"); 
     } 
    } 
0
如果你想週六或週日或每週的任何一天,但不超過本週

(週六,週日),我給你蓋上這段代碼。

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; 
} 
相關問題