The question may not be the clearest one but here is what I needed:
var date = new LocalDate(2020, 05, 05);
I need a date for Monday and Friday of the week in which the given date is.
The question may not be the clearest one but here is what I needed:
var date = new LocalDate(2020, 05, 05);
I need a date for Monday and Friday of the week in which the given date is.
I would suggest writing the code as a date adjuster:
public static class DayOfWeekAdjusters
{
public static Func<LocalDate, LocalDate> ForIsoDayOfWeek(IsoDayOfWeek dayOfWeek) =>
date => WeekYearRules.Iso.GetLocalDate(
WeekYearRules.Iso.GetWeekYear(date),
WeekYearRules.Iso.GetWeekOfWeekYear(date),
dayOfWeek);
}
Then you can use:
private static readonly Func<LocalDate, LocalDate> MondayAdjuster =
DayOfWeekAdjusters.ForIsoDayOfWeek(IsoDayOfWeek.Monday);
private static readonly Func<LocalDate, LocalDate> FridayAdjuster =
DayOfWeekAdjusters.ForIsoDayOfWeek(IsoDayOfWeek.Friday);
...
var date = new LocalDate(2020, 05, 05);
var monday = date.With(MondayAdjuster);
var friday = date.With(FridayAdjuster);
You can use those adjusters with LocalDateTime and OffsetDateTime too.
This is what I've come up with:
void Main()
{
var date = new LocalDate(2020, 05, 05);
var yearWeek = WeekYearRules.Iso.GetWeekOfWeekYear(date);
var monday = WeekYearRules.Iso.GetLocalDate(date.Year, yearWeek, IsoDayOfWeek.Monday);
var friday = WeekYearRules.Iso.GetLocalDate(date.Year, yearWeek, IsoDayOfWeek.Friday);
Console.WriteLine(monday);
Console.WriteLine(friday);
}
Or you can extract this logic into an extension method so you get:
void Main()
{
var date = new LocalDate(2020, 05, 05);
var monday = date.GetDateOfWeekDay(IsoDayOfWeek.Monday);
var friday = date.GetDateOfWeekDay(IsoDayOfWeek.Friday);
Console.WriteLine(monday);
Console.WriteLine(friday);
}
public static class LocalDateTimeExtensions {
// I coudn't come up with better name for this function, if you have any suggestions... :)
public static LocalDate GetDateOfWeekDay(this LocalDate date, IsoDayOfWeek dayOfWeek)
{
var currentWeekYear = WeekYearRules.Iso.GetWeekOfWeekYear(date);
return WeekYearRules.Iso.GetLocalDate(date.Year, currentWeekYear, dayOfWeek);
}
}