2010-01-25 64 views
33

Thư viện .NET có cách dễ dàng để trả lại số tuần cho một ngày cụ thể không? Ví dụ: đầu vào của Year = 2010, Month = 1, Day = 25, nên xuất số 5 cho số tuần.Tính tuần của tháng trong .NET

Gần nhất tôi thấy là Calendar.GetWeekOfYear, gần như ở đó.

Java có định dạng chuỗi ngày "W" trả về tuần trong tháng nhưng tôi không thể thấy bất kỳ điều gì tương đương trong .NET.

Trả lời

49

Không có được xây dựng theo cách để làm điều này nhưng đây là một phương pháp khuyến nông cần làm công việc cho bạn:

static class DateTimeExtensions { 
    static GregorianCalendar _gc = new GregorianCalendar(); 
    public static int GetWeekOfMonth(this DateTime time) { 
     DateTime first = new DateTime(time.Year, time.Month, 1); 
     return time.GetWeekOfYear() - first.GetWeekOfYear() + 1; 
    } 

    static int GetWeekOfYear(this DateTime time) { 
     return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday); 
    } 
} 

Cách sử dụng:

DateTime time = new DateTime(2010, 1, 25); 
Console.WriteLine(time.GetWeekOfMonth()); 

Output:

5 

Bạn có thể thay đổi GetWeekOfYear theo nhu cầu của mình.

4

Như quy định ở đây: http://forums.asp.net/t/1268112.aspx

bạn có thể sử dụng:

public static int Iso8601WeekNumber(DateTime dt) 
{ 
    return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); 
} 

public static int GetWeekOfMonth(DateTime dt) 
{  

    int weekOfYear = Iso8601WeekNumber(dt); 

    if (dt.Month == 1) 
    { 
     //week of year == week of month in January 
     //this also fixes the overflowing last December week 
     return weekOfYear; 
    } 

    int weekOfYearAtFirst = Iso8601WeekNumber(dt.AddDays(1 - dt.Day)); 
    return weekOfYear - weekOfYearAtFirst + 1; 
} 

Lưu ý nghĩ rằng nhu cầu của bạn có thể thay đổi như có một số lựa chọn thuật toán. I E. là một tuần có từ Thứ Hai đến Thứ Sáu vào cuối tháng Hai cũng là tuần đầu tiên của Tháng Ba hoặc tiêu chí nào xác định tuần "đầu tiên" của một tháng? ISO 8601: 2004 không đưa ra định nghĩa cho "Tuần trong tháng".

+0

Điều này không chính xác; nó trả về '-48' cho' dt = new DateTime (2010, 1, 25) '. – jason

+0

@ Jason Good catch. Vấn đề là vào ngày đầu tiên của tháng Giêng thuộc vào tuần cuối cùng của tháng Mười Hai. Cố định mã để bỏ qua điều đó. – GaussZ

18

Không có cách nào được tích hợp trực tiếp để thực hiện việc này nhưng có thể thực hiện khá dễ dàng. Dưới đây là một phương pháp khuyến nông có thể được sử dụng để dễ dàng có được số tuần trong năm dựa trên một ngày:

public static int GetWeekNumber(this DateTime date) 
{ 
    return GetWeekNumber(date, CultureInfo.CurrentCulture); 
} 

public static int GetWeekNumber(this DateTime date, CultureInfo culture) 
{ 
    return culture.Calendar.GetWeekOfYear(date, 
     culture.DateTimeFormat.CalendarWeekRule, 
     culture.DateTimeFormat.FirstDayOfWeek); 
} 

Sau đó chúng tôi có thể sử dụng để tính toán số tuần tháng dựa trên, loại giống như Jason shows. Một phiên bản thân thiện với văn hóa có thể trông giống như sau:

public static int GetWeekNumberOfMonth(this DateTime date) 
{ 
    return GetWeekNumberOfMonth(date, CultureInfo.CurrentCulture); 
} 

public static int GetWeekNumberOfMonth(this DateTime date, CultureInfo culture) 
{ 
    return date.GetWeekNumber(culture) 
     - new DateTime(date.Year, date.Month, 1).GetWeekNumber(culture) 
     + 1; // Or skip +1 if you want the first week to be 0. 
} 
+0

+ 1 dành cho văn hóa thân thiện – eddiegroves

+0

@eddiegroves: Cảm ơn bạn. Ít nhất ai cũng đánh giá cao nó: p – Svish

0

Đây là một chủ đề cũ nhưng tôi cần một cái gì đó như thế này và đây là những gì tôi nghĩ ra.

public static int WeekOfMonth(this DateTime date) 
{ 
    DateTime firstDayOfMonth = new DateTime(date.Year, date.Month, 1); 
    int firstDay = (int)firstDayOfMonth.DayOfWeek; 
    if (firstDay == 0) 
    { 
     firstDay = 7; 
    } 
    double d = (firstDay + date.Day - 1)/7.0; 
    return (int)Math.Ceiling(d); 
} 

Lưu ý: Điều này sẽ hoạt động nếu bạn muốn sử dụng thứ Hai là ngày đầu tiên của tuần. Nếu bạn muốn tuần bắt đầu vào Chủ nhật, điều này không thành công trong tuần thứ 2 của tháng 3 năm 2015 và có thể là các ngày khác. Thứ Hai, ngày 9 tháng 3 năm 2015 là ngày đầu tiên của tuần thứ hai. Phép tính ở trên trả về "3" cho ngày này. phiên bản

0
public int WeekCalc(DateTime dt) 
{ 
    CultureInfo ciCurr = CultureInfo.CurrentCulture; 
    int weekNum = ciCurr.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); 
    return weekNum; 
} 
2

@Svish

VB:

Public Shared Function GetWeekNumber(ByVal [date] As DateTime) As Integer 
    Return GetWeekNumber([date], CultureInfo.CurrentCulture) 
End Function 

Public Shared Function GetWeekNumber(ByVal [date] As DateTime, ByVal culture As CultureInfo) As Integer 
    Return culture.Calendar.GetWeekOfYear([date], culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek) 
End Function 

Public Shared Function GetWeekNumberOfMonth(ByVal [date] As DateTime) As Integer 
    Return GetWeekNumberOfMonth([date], CultureInfo.CurrentCulture) 
End Function 

Public Shared Function GetWeekNumberOfMonth(ByVal [date] As DateTime, ByVal culture As CultureInfo) As Integer 
    Return GetWeekNumber([date], culture) - GetWeekNumber(New DateTime([date].Year, [date].Month, 1), culture) + 1 
    ' Or skip +1 if you want the first week to be 0. 
End Function 
0

Khi bạn có dayOfWeek trong ngày đầu tiên của tháng, bạn có thể nhận được các tuần của tháng sử dụng số nguyên số học.

static class DateTimeExtensions 
{ 
    // Assumes that in current culture week starts on Sunday 
    public static int GetWeekOfMonth(this DateTimeOffset time) 
    { 
     DateTimeOffset first = new DateTimeOffset(time.Year, time.Month, 1, 0, 0, 0, time.Offset); 
     int firstSunday = (7 - (int)first.DayOfWeek) % 7 + 1; 
     int weekOfMonth = 1 + (time.Day + 7 - firstSunday)/7; 

     return weekOfMonth; 
    } 
} 
0

Điều gì đó đơn giản ...:)

private int WeeksNumber() 
     { 
      int daysInMonth = DateTime.DaysInMonth(YourYear, YourMonth); 
      DateTime date = new DateTime(Year, Month, 1); 
      switch (daysInMonth) 
      { 
       case 28: 
        { 
         if (date.DayOfWeek == DayOfWeek.Monday) 
         { 
          return 4; 
         } 
         else 
         { 
          return 5; 
         } 
        } 
       case 29: 
        { 
         return 5; 
        } 
       case 30: 
        { 
         if (date.DayOfWeek == DayOfWeek.Sunday) 
         { 
          return 6; 
         } 
         else 
         { 
          return 5; 
         } 
        } 
       case 31: 
        { 
         if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday) 
         { 
          return 6; 
         } 
         else 
         { 
          return 5; 
         } 
        } 
       default: return 5; 
      } 
     } 
11

Tiêu đề gây hiểu lầm. Câu hỏi thực sự là về số tuần dương lịch (số tuần nếu bạn tính các hàng trên lịch) của tháng, chứ không phải số tuần thực tế.

Đối với số tuần của tháng, bạn có thể sử dụng:

VB: 
    Function WeekNumber(TargetDate As Date) As Integer 
     Return (TargetDate.Day - 1) \ 7 + 1 
    End Function 

C#: 
    public int WeekNumber(DateTime TargetDate) 
    { 
     return (TargetDate.Day - 1)/7 + 1; 
    } 
+1

Tôi đồng ý rằng tiêu đề là gây hiểu lầm. Tôi đã cố gắng để tính toán, ví dụ, thứ hai thứ tư của tháng. Tuy nhiên, khi tôi viết bài kiểm tra đơn vị của mình bằng các câu trả lời khác được cung cấp theo câu hỏi này, một số kết quả không khớp với những gì tôi mong đợi. Điều này là bởi vì nếu ngày đầu tiên của tháng là thứ ba hoặc muộn hơn trong tuần, kết quả sẽ được giảm một tuần. Mã được cung cấp bởi câu trả lời này là những gì tôi đã kết thúc bằng cách sử dụng để giải quyết vấn đề. – user3308241

+1

Điều này không phù hợp với ví dụ. Ngày 1 tháng 1 năm 2010 là thứ Sáu, vì vậy tuần lịch đầu tiên chỉ có hai ngày. Kết quả là, ngày 25, thường sẽ rơi vào tuần thứ 4 sử dụng công thức này, thực sự là vào tuần thứ 5. Vì ví dụ nói rằng ngày 1 tháng 1 năm 2010 sẽ tạo ra tuần thứ 5, công thức trong câu trả lời này không thể đúng, bởi vì nó tạo ra tuần 4 (tức là (int ((25 - 1)/7) + 1) = 4. – Triynko

2

Đây là giải pháp của tôi:

static string GetWeekNumber() 
    { 

     var weekNumber = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, 
      DayOfWeek.Sunday) - 
     CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now.AddDays(1 - DateTime.Now.Day), 
      CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday) + 1; 

     switch (weekNumber) 
     { 
      case 1 : 
       return "First"; 
      case 2: 
       return "Second"; 
      case 3: 
       return "Third"; 
      default: 
       return "Fourth"; 
     } 
    } 
+0

Bạn có biết rằng có thể 6 tuần một tháng không? –

1

Dưới đây là một lựa chọn đơn giản nếu bạn muốn vòng 7 ngày đầu tiên được coi là tuần đầu tiên, ngay cả khi tháng không bắt đầu vào Chủ Nhật:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var dates = Enumerable.Range(0, 10) 
      .Select(r => new DateTime(2015, 10, 1).AddDays(r)) 
      .Select(q => new { Date = q, WeekOfMonth = q.WeekOfMonth() }); 

     foreach(var item in dates) 
     { 
      Console.WriteLine("Date: {0:ddd MM-dd-yyyy}, WOM: {1}", item.Date, item.WeekOfMonth); 
     } 

     var final = Console.ReadLine(); 
    } 
} 

public static class DateTimeExtensions 
{ 
    public static int WeekOfMonth(this DateTime d) 
    { 
     var isExact = (d.Day % 7 == 0); 
     var offset = isExact ? 0 : 1; 
     return (int)Math.Floor(d.Day/7.0) + offset; 
    } 
} 
0
Dim mdt As Date = txtDT.Text 
    Dim weekNum As Integer = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(mdt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday) - CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(GetFirstDayOfMonth(mdt), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday) + 1 
    Response.Write(weekNum) 
Các vấn đề liên quan