calendar_utils.dart 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import 'package:shared/utils/date_time_utils.dart';
  2. DateTime addDay(DateTime date, int days) {
  3. return date.add(Duration(days: days));
  4. }
  5. DateTime subtractDay(DateTime date, int days) {
  6. return date.subtract(Duration(days: days));
  7. }
  8. //一周的第一天从哪里开始,Sun 还是 Mon
  9. DateTime firstDayOfWeek(DateTime date) {
  10. //返回星期天开始
  11. // if (date.weekday == DateTime.sunday) {
  12. // return date;
  13. // }
  14. // return date.subtract(Duration(days: date.weekday));
  15. // 从星期一开始
  16. return date.subtract(Duration(days: date.weekday - 1));
  17. }
  18. //是否包含选中的日期
  19. bool hasSelectedDate(List<DateTime> list, DateTime selected) {
  20. for (DateTime date in list) {
  21. // 格式化日期并进行比较
  22. if (DateTimeUtils.formatDate(date, format: 'yyyyMMdd') == DateTimeUtils.formatDate(selected, format: 'yyyyMMdd')) {
  23. return true;
  24. }
  25. }
  26. return false;
  27. }
  28. // 检查日期是否小于今天
  29. bool isPastDate(DateTime now, DateTime date) {
  30. // 获取当前日期的凌晨时间
  31. DateTime todayMidnight = DateTime(now.year, now.month, now.day);
  32. // 判断给定日期是否小于今天的凌晨时间
  33. return date.isBefore(todayMidnight);
  34. }
  35. // =================================== 获取一周的数据 ↓ ===================================
  36. List<DateTime> getWeekdays(DateTime date, int at) {
  37. final first = firstDayOfWeek(date);
  38. if (at >= 0) {
  39. return _addWeek(first, at);
  40. } else {
  41. return _subtractWeek(first, -at);
  42. }
  43. }
  44. List<DateTime> _addWeek(DateTime date, int add) {
  45. final day = addDay(date, 7 * add);
  46. return _getWeekDaysAt(day);
  47. }
  48. List<DateTime> _subtractWeek(DateTime date, int subtract) {
  49. final day = subtractDay(date, 7 * subtract);
  50. return _getWeekDaysAt(day);
  51. }
  52. List<DateTime> _getWeekDaysAt(DateTime date) {
  53. return List.generate(7, (index) => index).map((index) => date.add(Duration(days: index))).toList();
  54. }
  55. // =================================== 获取二周的数据 ↓ ===================================
  56. List<DateTime> get2Weekdays(DateTime date, int at) {
  57. final first = firstDayOfWeek(date);
  58. if (at >= 0) {
  59. return _add2Week(first, at);
  60. } else {
  61. return _subtract2Week(first, -at);
  62. }
  63. }
  64. List<DateTime> _add2Week(DateTime date, int add) {
  65. final day = addDay(date, 14 * add);
  66. return _get2WeekDaysAt(day);
  67. }
  68. List<DateTime> _subtract2Week(DateTime date, int subtract) {
  69. final day = subtractDay(date, 14 * subtract);
  70. return _get2WeekDaysAt(day);
  71. }
  72. List<DateTime> _get2WeekDaysAt(DateTime date) {
  73. return List.generate(14, (index) => index).map((index) => date.add(Duration(days: index))).toList();
  74. }