Flutter日期操作之计算周

Flutter中的日期相关类是Dart语言的DateTime类。而这个类只提供了基本的日期相关信息。这里提供一种计算从1970年1月1日开始的周数计算方法:

  static const int EPOCH_WEEK_DAY = DateTime.thursday;

  static const int EPOCH_MILLIS_SECONDS = 0;

  static const int EPOCH_JULIAN_DAY = 0;

  static int weekSinceEpoch(DateTime dateTime, int weekStart) {
    DateTime epoch = DateTime.utc(1970);
    dateTime = new DateTime.utc(dateTime.year, dateTime.month, dateTime.day);

    int offset = EPOCH_WEEK_DAY - weekStart;
    if (offset < 0) {
      offset += 7;
    }

    int delta = EPOCH_JULIAN_DAY - offset;

    return (dateTime.difference(epoch).inDays - delta) ~/ 7;
  }

其中weekStart可根据Localizations获取

DateTime now = DateTime.now();
    MaterialLocalizations localizations = MaterialLocalizations.of(context);
    int weekSinceEpoch = DateUtils.weekSinceEpoch(now,
                                    localizations.firstDayOfWeekIndex);

你可能感兴趣的:(Flutter日期操作之计算周)