flutter - 如何在Dart逻辑中获取每周日期列表

标签 flutter dart

有谁能帮助我获得选择给定月份中每个星期的日期列表,以及选择星期一或其他任何一个星期几的开始时间。

无法弄清楚抖动的逻辑( Dart )

例如 :

input :
Month : May
weekday : Monday



输出:
[
  {
    "week1": [
      "-",
      "-",
      "-",
      "-",
      "2020-05-01",
      "2020-05-02",
      "2020-05-03"
    ]
  },
  {
    "week2": [
      "2020-05-04",
      "2020-05-05",
      "2020-05-06",
      "2020-05-07",
      "2020-05-08",
      "2020-05-09",
      "2020-05-10"
    ]
  },
  {
    "week3": [
      "2020-05-11",
      "2020-05-12",
      "2020-05-13",
      "2020-05-14",
      "2020-05-15",
      "2020-05-16",
      "2020-05-17"
    ]
  },
  {
    "week4": [
      "2020-05-18",
      "2020-05-19",
      "2020-05-20",
      "2020-05-21",
      "2020-05-22",
      "2020-05-23",
      "2020-05-24"
    ]
  },
  {
    "week5": [
      "2020-05-25",
      "2020-05-26",
      "2020-05-27",
      "2020-05-28",
      "2020-05-29",
      "2020-05-30",
      "2020-05-31"
    ]
  }
]

最佳答案

终于我找到了解决方案。张贴在这里供他人将来使用

  calculateWeeks(DateTime currentMonth, DateTime previousMonth) {
  List<List<String>> weeks = [];
  currentMonth = DateTime.utc(2020, DateTime.august, 1);
  if (currentMonth == null) {
    currentMonth = DateTime.now();
  }

  int firstDay = 1;
  int lastDay = DateUtils.daysofMonth(currentMonth);
  log('Day from $firstDay - $lastDay');
  DateTime startMonth =
      DateTime.utc(currentMonth.year, currentMonth.month, firstDay);
  DateTime endMonth =
      DateTime.utc(currentMonth.year, currentMonth.month, lastDay);

  DateTime weekStartDates = DateUtils.weekStart(startMonth);
  DateTime weekEndDates = DateUtils.weekEnd(endMonth);
  int daysDiff = weekEndDates.difference(weekStartDates).inDays;
  log('Start week : $weekStartDates');
  log('End   week : $weekEndDates');
  log('Diff       : ${daysDiff}');
  List<String> weekly = [];
  for (int i = 0; i < daysDiff; i++) {
    String date = '';
    DateTime checkdate = weekStartDates.add(Duration(days: i));
    if ((checkdate == startMonth || checkdate.isAfter(startMonth)) &&
        (checkdate == endMonth || checkdate.isBefore(endMonth))) {
      log('weekday : $i - $checkdate : ${checkdate.weekday}');
      date = checkdate.toIso8601String();
    }
    weekly.add(date);
    if (checkdate.weekday == 7 || i == daysDiff - 1) {
      weeks.add(weekly);
      weekly = [];
    }
  }
  log('Weekly Dates :${json.encode(weeks)}');
}

关于flutter - 如何在Dart逻辑中获取每周日期列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61731275/

相关文章:

android - 如何自定义 SearchDelegate(创建自定义搜索字段)

flutter - Flutter中的复选框

flutter - 如何在Flutter中正确对齐文本?

firebase - Flutter firebase sendSignInLinkToEmail 不发送电子邮件并报告任何错误 iOS

image - 尝试显示超过 10 张图像时 Flutter 应用程序崩溃

Flutter 仅带有左上角和右上角的上边框

flutter - 如何在Flutter中使用drawLine()和drawCircle()绘制4条等距离线的圆

flutter - 如何使文本窗口小部件的大小随内容变化而变化?

android - 如何解决任务 ':app:compileFlutterBuildDebug' 执行失败

flutter - Flutter在TextField小部件上未显示BLoC流值