0
在C#中,我如何查找當前日期的星期,我正在嘗試獲取當前日期的星期編號,您能否幫助我,謝謝。查找周,使用當前日期?在C#中?
在C#中,我如何查找當前日期的星期,我正在嘗試獲取當前日期的星期編號,您能否幫助我,謝謝。查找周,使用當前日期?在C#中?
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)
如果您需要本週的「全球」號碼,您可以使用此:
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);
如果您需要在一個月星期數,使用不便像這樣的代碼:
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;
請注意,如果您希望與ISO8601兼容的星期,這將不匹配。你需要使用像這樣的東西:http://blogs.msdn.com/b/shawnste/archive/2006/01/24/iso-8601-week-of-year-format-in-microsoft-net.aspx – porges 2012-04-04 05:41:47
你好,謝謝你,科林先生,這很好,但我想得到當前的一個星期[當前日期],你能幫助我嗎?在當前的月份當前日期星期,星期1星期2 ...星期5那樣 – 2012-04-04 05:57:00