Flutter:弄错一周中的几天

Flutter: Get Wrong days of the week

从星期一到星期四,我得到了正确的日子,但从星期五开始,我得到了错误的日子。为什么?

代码示例:

Text(DateFormat('EEEE').format(DateTime(DateTime.friday))),

然后我得到星期六。这是一个错误吗?

这不是错误,DateTime() 默认构造函数将 year 作为第一个参数:

  DateTime(int year,
      [int month = 1,
      int day = 1,
      int hour = 0,
      int minute = 0,
      int second = 0,
      int millisecond = 0,
      int microsecond = 0])
      : this._internal(year, month, day, hour, minute, second, millisecond,
            microsecond, false);

所以这段代码:

DateTime date = DateTime(DateTime.friday);

本质上是构造第5年的DateTime,因为DateTime.friday无非是等于5的const int

  static const int monday = 1;
  static const int tuesday = 2;
  static const int wednesday = 3;
  static const int thursday = 4;
  static const int friday = 5;
  static const int saturday = 6;
  static const int sunday = 7;
  static const int daysPerWeek = 7;

格式化为 DateFormat returns 星期六恰好是一年中的第一天:

import 'dart:core';
import 'package:intl/intl.dart';

main() {
  DateTime date = DateTime(DateTime.friday); // creates a DateTime of the year 5
  print(date.year);    // year: 5
  print(date.month);   // month: Jan (default = 1)
  print(date.weekday); // day: Saturday (first day of the year)
  print("${date.year}-${date.month}-${date.day}"); // 5-1-1
}

DateTime 应该用于定义特定的 日期和时间 ,例如 Friday 11th Dec 2020,它不能被使用定义任何星期五。