Skip to content

Instantly share code, notes, and snippets.

@AlexV525
Created August 23, 2020 08:45
Show Gist options
  • Select an option

  • Save AlexV525/420817392ee3b28dcac436da55a75e84 to your computer and use it in GitHub Desktop.

Select an option

Save AlexV525/420817392ee3b28dcac436da55a75e84 to your computer and use it in GitHub Desktop.
Get specific weekday in month (null-safety version)
void main() {
print(getSpecificWeekdayInMonth(
year: 2020,
month: 8,
whichWeek: 5,
whichWeekday: 7,
));
}
DateTime? getSpecificWeekdayInMonth({
required int year,
required int month,
required int whichWeek,
required int whichWeekday,
}) {
if (year < 1 || month < 1 || whichWeek < 1 || whichWeekday < 1) {
throw ArgumentError('Everthing must more than 1');
}
final DateTime baseDate = DateTime(year, month, 1);
/// Use first monday for the date offset.
DateTime firstMonday;
if (baseDate.weekday == 1) {
firstMonday = baseDate;
} else {
firstMonday = baseDate.add(Duration(days: 8 - baseDate.weekday));
}
/// Return if requested for first monday.
if (whichWeek == 1 && whichWeekday == 1) {
return firstMonday;
}
/// Reduce 1 day for validation.
final Duration offsetDuration = Duration(
days: (whichWeek - 1) * 7 + whichWeekday - 1,
);
final DateTime calcDate = firstMonday.add(offsetDuration);
/// If the result is out of the constraint, return nothing.
if (calcDate.year != year || calcDate.month != month) {
return null;
}
return calcDate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment