calendar_utils.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. DateTime addDay(DateTime date, int days) {
  2. return date.add(Duration(days: days));
  3. }
  4. DateTime subtractDay(DateTime date, int days) {
  5. return date.subtract(Duration(days: days));
  6. }
  7. DateTime firstDayOfWeek(DateTime date) {
  8. if (date.weekday == DateTime.sunday) {
  9. return date;
  10. }
  11. return date.subtract(Duration(days: date.weekday));
  12. }
  13. // =================================== 获取一周的数据 ↓ ===================================
  14. List<DateTime> getWeekdays(DateTime date, int at) {
  15. final first = firstDayOfWeek(date);
  16. if (at >= 0) {
  17. return _addWeek(first, at);
  18. } else {
  19. return _subtractWeek(first, -at);
  20. }
  21. }
  22. List<DateTime> _addWeek(DateTime date, int add) {
  23. final day = addDay(date, 7 * add);
  24. return _getWeekDaysAt(day);
  25. }
  26. List<DateTime> _subtractWeek(DateTime date, int subtract) {
  27. final day = subtractDay(date, 7 * subtract);
  28. return _getWeekDaysAt(day);
  29. }
  30. List<DateTime> _getWeekDaysAt(DateTime date) {
  31. return List.generate(7, (index) => index)
  32. .map((index) => date.add(Duration(days: index)))
  33. .toList();
  34. }
  35. // =================================== 获取二周的数据 ↓ ===================================
  36. List<DateTime> get2Weekdays(DateTime date, int at) {
  37. final first = firstDayOfWeek(date);
  38. if (at >= 0) {
  39. return _add2Week(first, at);
  40. } else {
  41. return _subtract2Week(first, -at);
  42. }
  43. }
  44. List<DateTime> _add2Week(DateTime date, int add) {
  45. final day = addDay(date, 14 * add);
  46. return _get2WeekDaysAt(day);
  47. }
  48. List<DateTime> _subtract2Week(DateTime date, int subtract) {
  49. final day = subtractDay(date, 14 * subtract);
  50. return _get2WeekDaysAt(day);
  51. }
  52. List<DateTime> _get2WeekDaysAt(DateTime date) {
  53. return List.generate(14, (index) => index)
  54. .map((index) => date.add(Duration(days: index)))
  55. .toList();
  56. }