我想知道如何根据一年中星期几的序数来计算一周中的星期几。例如,我要处理第33周,我应该知道八月是第二周。 我已经计算了几个月,但现在我要处理几个星期。
我已经有解决方案了,但是对我来说似乎很肮脏。
代码如下:
var data = query.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.CreatedDate ?? DateTime.UtcNow, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.Select(article => new ArticleSimpleObject
{
Week = GetWeekNumberOfMonth(article.FirstOrDefault().CreatedDate.Value),
Amount = article.Sum(x => x.Amount),
Month = article.FirstOrDefault().CreatedDate.Value.Month
});
这是我用来获取周数的方法:
private static int GetWeekNumberOfMonth(DateTime date)
{
date = date.Date;
DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
if (firstMonthMonday > date)
{
firstMonthDay = firstMonthDay.AddMonths(-1);
firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
}
return (date - firstMonthMonday).Days / 7 + 1;
}
在我写给大家的时候,这种解决方案有效,
但是我个人不喜欢它,我想还有一个更优雅的解决方案,这就是为什么如果有经验的人帮助我们解决这个问题,我会发布此问题以帮助自己和将来的读者:)
也许可以根据日历类https://docs.microsoft.com/en-us/dotnet/api/system.globalization.calendar?view=netframework-4.8
解决此问题我已经尝试了一些变体,但是我什至没有解决它。.
谢谢大家
欢呼
答案 0 :(得分:-1)
一种方法是从日期的那年的那一周减去该日期的那一天的那一天的星期。像这样:
void Main()
{
Console.WriteLine(DateTime.Now.GetWeekOfMonth());
}
public static class MyDateTimeExtensions
{
private static GregorianCalendar _calendar = new GregorianCalendar();
public static int GetWeekOfMonth(this DateTime date)
{
return
date.GetWeekOfYear()
- new DateTime(date.Year, date.Month, 1).GetWeekOfYear()
+ 1;
}
private static int GetWeekOfYear(this DateTime date)
{
return _calendar.GetWeekOfYear(
date,
CalendarWeekRule.FirstDay,
DayOfWeek.Sunday);
}
}
这将输出当前日期的4个:2019年9月23日。
答案 1 :(得分:-1)
您可以编写一些通用扩展来对此进行简单计算。
首先,您需要从一周的特定日期开始的一周的第一天作为日期:
public static DateTime FirstDateOfWeekStarting(this DateTime aDate, DayOfWeek dow) => aDate.Date.AddDays((int)dow - (int)aDate.DayOfWeek);
然后,您可以轻松地将第一个日期的月份中的日期转换为月份中的周号:
public static int WeekStartingDOWNumOfMonth(this DateTime aDate, DayOfWeek dow) => (aDate.FirstDateOfWeekStarting(dow).Day-1) / 7 + 1;
对于您从星期一开始的几周的特定情况,
public static int WeekStartingMonNumOfMonth(this DateTime aDate) => aDate.WeekStartingDOWNumOfMonth(DayOfWeek.Monday);