using System;
using System.Linq;
namespace Abp.Extensions
{
///
/// Extension methods for .
///
public static class DayOfWeekExtensions
{
///
/// Check if a given value is weekend.
///
public static bool IsWeekend(this DayOfWeek dayOfWeek)
{
return dayOfWeek.IsIn(DayOfWeek.Saturday, DayOfWeek.Sunday);
}
///
/// Check if a given value is weekday.
///
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
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.
///
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.
///
public static int TotalInstancesInMonth(this DayOfWeek dayOfWeek, DateTime dateTime)
{
return dayOfWeek.TotalInstancesInMonth(dateTime.Year, dateTime.Month);
}
}
}