using System;
using System.ComponentModel;
using System.Linq;
namespace JiShe.CollectBus.Common.Extensions
{
///
/// Extension methods for .
///
public static class DayOfWeekExtensions
{
///
/// Check if a given value is weekend.
///
[Description("检查给定值是否为周末")]
public static bool IsWeekend(this DayOfWeek dayOfWeek)
{
return dayOfWeek.IsIn(DayOfWeek.Saturday, DayOfWeek.Sunday);
}
///
/// Check if a given value is weekday.
///
[Description("检查给定值是否为工作日")]
public static bool IsWeekday(this DayOfWeek dayOfWeek)
{
return dayOfWeek.IsIn(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday);
}
///
/// Finds the NTH week day of a month.
///
/// The day of week.
/// The year.
/// The month.
/// The nth instance.
/// Compensates for 4th and 5th DayOfWeek of Month
[Description("查找一个月的第n周")]
public static DateTime FindNthWeekDayOfMonth(this DayOfWeek dayOfWeek, int year, int month, int n)
{
if (n < 1 || n > 5)
{
throw new ArgumentOutOfRangeException(nameof(n));
}
var y = 0;
var daysOfMonth = DateTimeExtensions.DaysOfMonth(year, month);
// compensate for "last DayOfWeek in month"
var totalInstances = dayOfWeek.TotalInstancesInMonth(year, month);
if (n == 5 && n > totalInstances)
n = 4;
var foundDate = daysOfMonth
.Where(date => dayOfWeek.Equals(date.DayOfWeek))
.OrderBy(date => date)
.Select(x => new { n = ++y, date = x })
.Where(x => x.n.Equals(n)).Select(x => x.date).First(); //black magic wizardry
return foundDate;
}
///
/// Finds the total number of instances of a specific DayOfWeek in a month.
///
/// The day of week.
/// The year.
/// The month.
///
[Description("获取一个月内特定DayOfWeek的实例总数")]
public static int TotalInstancesInMonth(this DayOfWeek dayOfWeek, int year, int month)
{
return DateTimeExtensions.DaysOfMonth(year, month).Count(date => dayOfWeek.Equals(date.DayOfWeek));
}
///
/// Gets the total number of instances of a specific DayOfWeek in a month.
///
/// The day of week.
/// The date in a month.
///
[Description("获取一个月内特定DayOfWeek的实例总数")]
public static int TotalInstancesInMonth(this DayOfWeek dayOfWeek, DateTime dateTime)
{
return dayOfWeek.TotalInstancesInMonth(dateTime.Year, dateTime.Month);
}
}
}