3 回答

TA貢獻(xiàn)1951條經(jīng)驗 獲得超3個贊
沒有內(nèi)置的方法可以執(zhí)行此操作,但是這里有一個擴(kuò)展方法可以為您完成這項工作:
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);
}
}
用法:
DateTime time = new DateTime(2010, 1, 25);
Console.WriteLine(time.GetWeekOfMonth());
輸出:
5
您可以GetWeekOfYear根據(jù)需要進(jìn)行更改。

TA貢獻(xiàn)1812條經(jīng)驗 獲得超5個贊
沒有直接內(nèi)置的方法可以做到這一點(diǎn),但是可以很容易地做到。這是一種擴(kuò)展方法,可用于輕松獲取日期的基于年份的星期數(shù):
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);
}
然后,我們可以使用它來計算基于月份的星期數(shù),就像Jason所示。文化友好版本可能如下所示:
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.
}
- 3 回答
- 0 關(guān)注
- 799 瀏覽
添加回答
舉報