1

Yesterday, my app suddenly failed. So after hours of debugging, it came down to this.

  test("What The Flutter", () {
    final a = "2023-03-13T00:00:00.000";
    final b = "2023-03-12T00:00:00.000";
    final diff = DateTime.parse(a).difference(DateTime.parse(b));
    print(diff.inDays);
    expect(diff.inDays, 1); // this fails. it says it is 0
  });

I suppose it has something to do with something invented in 1895 but not sure and how to write a code to handle this ?

For reference, this passes

  test("All Correct after the anomaly day", () {
    final a = "2023-03-14T00:00:00.000";
    final b = "2023-03-13T00:00:00.000";
    final diff = DateTime.parse(a).difference(DateTime.parse(b));
    print(diff.inDays);
    expect(diff.inDays, 1);
  });

Forcing the dates to UTC is not helping

final diff = DateTime.parse(a).toUtc().difference(DateTime.parse(b).toUtc());

This questions is addressing a specific case of dates not behaving as intended, not asking how to find the difference between two dates like this one Flutter: Find the number of days between two dates

TSR
  • 17,242
  • 27
  • 93
  • 197
  • Sunday morning's switchover to DST may have something to do with it, based on the date's that work and the ones that don't. – Ken White Mar 14 '23 at 22:08
  • "This questions is addressing a specific case of dates not behaving as intended, not asking how to find the difference between two dates..." The answers for the linked question discuss the specific problem of computing differences in days when a DST change occurs and why you can't simply use `a.difference(b).inDays`. – jamesdlin Mar 14 '23 at 23:41

1 Answers1

0

The problem is that you are parsing a date that is not UTC. To know it is UTC, it ends with Z

  test("What The Flutter", () {
    final a = "2023-03-13T00:00:00.000Z";
    final b = "2023-03-12T00:00:00.000Z";
    final diff = DateTime.parse(a).difference(DateTime.parse(b));
    print(diff.inDays);
    expect(diff.inDays, 1); // this should pass. let me know if you have any further question regarding this
  });

The documentation says :

  /// If the dates above had been in local time, not UTC, then the difference
  /// between two midnights may not be a multiple of 24 hours due to daylight
  /// saving differences.
TSR
  • 17,242
  • 27
  • 93
  • 197