Flutter: Get Wrong days of the week

Issue

from Monday – Thursday, I get the right days, but from Friday, I get the wrong days. Why?

Code example:

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

And i get Saturday. Is that a bug?

Solution

It’s not a bug, DateTime() default constructor takes year as the first argument:

  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);

So this code:

DateTime date = DateTime(DateTime.friday);

Is essentially constructing a DateTime of the year 5, because DateTime.friday is nothing more than a const int that equals to 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;

Formatting with DateFormat returns Saturday which happens to be the first day of the year:

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 should be used to define a specific Date and Time, for example, Friday 11th Dec 2020, it can’t be used to define any Friday.

Answered By – Stefano Amorelli

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *