在 .NET 中计算月份中的一周 [英] Calculate week of month in .NET
本文介绍了在 .NET 中计算月份中的一周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
.NET 库是否有返回给定日期的周数的简单方法?例如输入Year = 2010, Month = 1, Day = 25
,应该输出5
作为周数.
Do the .NET libraries have an easy way of returning the week number for a given date? For example, input of Year = 2010, Month = 1, Day = 25
, should output 5
for the week number.
我发现最近的是 Calendar.GetWeekOfYear
,几乎就在那里.
Closest I found was Calendar.GetWeekOfYear
, which is almost there.
Java 有一个日期字符串格式W",它按月返回一周,但我在 .NET 中看不到任何等效的东西.
Java has a date string format "W" which returns week in month but I can't see anything equivalent in .NET.
推荐答案
没有内置的方法可以做到这一点,但这里有一个扩展方法可以为您完成这项工作:
There is no built in way to do this but here is an extension method that should do the job for you:
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
.
这篇关于在 .NET 中计算月份中的一周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文