kreta/Kreta.BusinessLogic/Classes/DateHelper.cs
2024-03-13 00:33:46 +01:00

42 lines
1.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Globalization;
namespace Kreta.BusinessLogic.Classes
{
public static class DateHelper
{
// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetISO8601WeekOfYear(this DateTime date)
{
var calendar = CultureInfo.InvariantCulture.Calendar;
// Seriously cheat. If its Monday, Tuesday or Wednesday, then itll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = calendar.GetDayOfWeek(date);
if (DayOfWeek.Monday <= day && day <= DayOfWeek.Wednesday)
{
date = date.AddDays(3);
}
// Return the week of our adjusted day
return calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
public static int GetISO8601WeekOfYear(this DateTime? date)
{
if (date.HasValue)
{
return date.Value.GetISO8601WeekOfYear();
}
return GetWeeksInYear();
}
private static int GetWeeksInYear()
{
return GetISO8601WeekOfYear(new DateTime(DateTime.Now.Year, 12, 31));
}
}
}