0

在 C# 中如何找到当前日期的星期,我正在尝试获取当前日期的星期数,您能帮帮我吗,谢谢。

4

2 回答 2

3

请参阅Calendar.GetWeekOfYear

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
      DateTime date1 = new DateTime(2011, 1, 1);
      Calendar cal = dfi.Calendar;

      Console.WriteLine("{0:d}: Week {1} ({2})", date1, 
                        cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, 
                                          dfi.FirstDayOfWeek),
                        cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));       
   }
}
// The example displays the following output:
//       1/1/2011: Week 1 (GregorianCalendar)
于 2012-04-04T05:34:46.313 回答
0

如果您需要本周的“全球”号码,您可以使用这个:

using System;
using System.Globalization;    

DateTime date = DateTime.Now;
int res = 0;

// First day of year
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

// (Default) First four day week from Sunday
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday);

// First four day week from StartOfWeek
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

// First full week from Sunday
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);

// First full week from StartOfWeek
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek); 

如果您需要一个月中的周数,请像这样的代码使用 smth:

 DateTime beginningOfMonth = DateTime.Now;

 while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
     date = date.AddDays(1);

 int result = (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;
于 2012-04-04T07:07:37.160 回答