42 lines
1.3 KiB
C#
42 lines
1.3 KiB
C#
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 it’ll
|
||
// 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));
|
||
}
|
||
}
|
||
}
|