Home > Software engineering >  How to get DateTime with zeroed time in Flutter
How to get DateTime with zeroed time in Flutter

Time:11-10

I'm new to Flutter and I'm trying to output the start of the current day in UTC format. I use Flutter 3.3.7 and Dart SDK 2.18.4.

First, I take the current date.

DateTime dt = DateTime.now();

Next, I use extension for the DateTime class, which I implemented myself.

extension DateTimeFromTimeOfDay on DateTime {
  DateTime appliedFromTimeOfDay(TimeOfDay timeOfDay) {
    return DateTime(year, month, day, timeOfDay.hour, timeOfDay.minute);
  }
}

It outputs the same date, only with the time that I pass it via TimeOfDay class(In this case 00:00).

dt = dt.appliedFromTimeOfDay(const TimeOfDay(hour: 0, minute: 0));
  print(dt.toUtc()); //2022-11-08 21:00:00.000Z

But when I run this code, it outputs a date with a non-zero time.

I also tried adding the toUtc() method to the extension.

extension DateTimeFromTimeOfDay on DateTime {
  DateTime appliedFromTimeOfDay(TimeOfDay timeOfDay) {
    return DateTime(year, month, day, timeOfDay.hour, timeOfDay.minute).toUtc();
  }
}

That didn't work either.

How can I get the DateTime in UTC format with zeroed time of day? For example, 2022-11-08 00:00:00.000Z

CodePudding user response:

Try it with this extension method

extension DateTimeExtension on DateTime {
    DateTime getDateOnly() {
        return DateTime(this.year, this.month, this.day);
    }
}

CodePudding user response:

DateTime has a utc constructor that allows you to do this.

extension DateTimeFromTimeOfDay on DateTime {
  DateTime appliedFromTimeOfDay(TimeOfDay timeOfDay) {
    return DateTime.utc(year, month, day, timeOfDay.hour, timeOfDay.minute);
  }
}

DateTime today = DateTime.now()
  .appliedFromTimeOfDay(const TimeOfDay(hour: 0, minute: 0)); // output: 2022-11-09 00:00:00.000Z (note the Z which indicate UTC)
  • Related