Skip to content

Instantly share code, notes, and snippets.

@rafaelqueiroz88
Created October 25, 2023 13:02
Show Gist options
  • Save rafaelqueiroz88/6734f20090117c81bbc0651698c04006 to your computer and use it in GitHub Desktop.
Save rafaelqueiroz88/6734f20090117c81bbc0651698c04006 to your computer and use it in GitHub Desktop.
Find first and last DateTime of a week
void main() {
// Find first date and last date of CURRENT WEEK
DateTime today = DateTime.now();
print(findFirstDateOfTheWeek(today));
print(findLastDateOfTheWeek(today));
// Find first date and last date of any provided date
DateTime date = DateTime.parse('2023-09-01');
print(findFirstDateOfTheWeek(date));
print(findLastDateOfTheWeek(date));
}
// return DateTime containing the first DateTime of a Week
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
// return DateTime containing the last DateTime of a Week
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
/**
* Other stuff
* var now = new DateTime.now();
* var now_1w = now.subtract(Duration(days: 7));
* var now_1m = new DateTime(now.year, now.month-1, now.day);
* var now_1y = new DateTime(now.year-1, now.month, now.day);
* print(now_1w);
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment