3 回答
TA贡献1951条经验 获得超3个赞
没有内置的方法可以执行此操作,但是这里有一个扩展方法可以为您完成这项工作:
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根据需要进行更改。
TA贡献1812条经验 获得超5个赞
没有直接内置的方法可以做到这一点,但是可以很容易地做到。这是一种扩展方法,可用于轻松获取日期的基于年份的星期数:
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);
}
然后,我们可以使用它来计算基于月份的星期数,就像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 关注
- 748 浏览
添加回答
举报