skip to Main Content

The following code returns a date that is off by several minutes (note that I am running in US Central DST):

      final givenDate = DateTime.parse('1980-01-03T11:05:16Z');
      const expectedDateString = '01/03/1980 11:05:16';

      print("givenDate is ${givenDate.toString()}");
      print(
          "DateFormat('MM/dd/yyyy HH:MM:ss').format(givenDate) is ${DateFormat('MM/dd/yyyy HH:MM:ss').format(givenDate)}");

The prints show:

givenDate is 1980-01-03 11:05:16.000Z

DateFormat(‘MM/dd/yyyy HH:MM:ss’).format(givenDate) is 01/03/1980 11:01:16

Four minutes off. The formatted date/time should be 01/03/1980 11:05:16

Changing the constants:

      final givenDate = DateTime.parse('1980-01-03T11:45:16.735Z');
      const expectedDateString = '01/03/1980 11:45:16';

Results in:

givenDate is 1980-01-03 11:45:16.735Z

DateFormat(‘MM/dd/yyyy HH:MM:ss’).format(givenDate) is 01/03/1980 11:01:16

The minutes portion is still ’01’. It should be 45.

I am running:

Flutter version 3.10.0 on channel stable

Dart version 3.0.0

intl: ^0.18.1 (same issue with 0.18.0)

2

Answers


  1. Your format is incorrect. MM means month and mm means minute. (You are printing the month not the minute in the time.)

    Change DateFormat('MM/dd/yyyy HH:MM:ss') to DateFormat('MM/dd/yyyy HH:mm:ss')

    Login or Signup to reply.
  2. MM stands for Month and mm stands for minutes and you are printing month instead of minutes replace the MM with mm where minutes should be there

    So your code should be like this

    final givenDate = DateTime.parse('1980-01-03T11:05:16Z');
    const expectedDateString = '01/03/1980 11:05:16';
    
    print("givenDate is ${givenDate.toString()}");
    print("DateFormat('MM/dd/yyyy HH:mm:ss').format(givenDate) is ${DateFormat('MM/dd/yyyy HH:mm:ss').format(givenDate)}");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search