【问题标题】:Get current Week of the Month as a Number以数字形式获取本月的当前周
【发布时间】:2020-01-21 11:04:51
【问题描述】:

如何在 Dart 中以数字形式获取当月的当前周?我需要创建某种带有周视图的日历,上面写着“2. 一月的一周”

【问题讨论】:

  • 你找到答案了吗?我现在有同样的问题))

标签: flutter dart


【解决方案1】:
extension DateTimeExtension on DateTime {
  int get weekOfMonth {
    var wom = 0;
    var date = this;

    while (date.month == month) {
      wom++;
      date = date.subtract(const Duration(days: 7));
    }

    return wom;
  }
}

然后像这样使用它:

var wom = DateTime.now().weekOfMonth;

【讨论】:

  • 嗨,@dblank 这个代码是在生产环境中测试的。我在这里找不到任何错误,但很高兴知道它是否经过测试。谢谢
【解决方案2】:

您可以使用 DateTime().now() 来获取系统的当前时间和日期或今天的日期。下面是sn-p的代码:

// Current date and time of system
  String date = DateTime.now().toString();

// This will generate the time and date for first day of month
  String firstDay = date.substring(0, 8) + '01' + date.substring(10);

// week day for the first day of the month
  int weekDay = DateTime.parse(firstDay).weekday;

  DateTime testDate = DateTime.now();

  int weekOfMonth;

//  If your calender starts from Monday
  weekDay--;
  weekOfMonth = ((testDate.day + weekDay) / 7).ceil();
  print('Week of the month: $weekOfMonth');
  weekDay++;

// If your calender starts from sunday
  if (weekDay == 7) {
    weekDay = 0;
  }
  weekOfMonth = ((testDate.day + weekDay) / 7).ceil();
  print('Week of the month: $weekOfMonth');

或者,如果正在寻找日历月份 UI 的完整实现,那么 click here

【讨论】:

  • 如果日历从星期一开始怎么办
  • 我已经更新了答案并添加了代码来处理这两种情况。您将在更新后的代码中找到答案。
猜你喜欢
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多