1

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

代码示例:

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

我得到星期六。那是一个错误吗?

4

1 回答 1

1

这不是错误,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);

本质上是在构造DateTime5 年的 a,因为DateTime.friday无非就是 aconst int等于 5:

  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返回星期六,恰好是一年的第一天:

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,它不能用于定义任何星期五。

于 2020-12-09T16:08:50.410 回答