Aidar Nafikov
Aidar Nafikov

Reputation: 13

How to get DateTime with zeroed time in Flutter

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

Upvotes: 1

Views: 2220

Answers (3)

Tatsuya Fujisaki
Tatsuya Fujisaki

Reputation: 1991

You can use DateUtils.dateOnly.

import 'package:flutter/material.dart';

DateTime dateTime = DateTime.now(); // 2024-01-01 01:23:45.123456
DateTime dateOnly = DateUtils.dateOnly(dateTime); // 2024-01-01 00:00:00.000

Upvotes: 0

Austin
Austin

Reputation: 121

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)

Upvotes: 1

Ozan Taskiran
Ozan Taskiran

Reputation: 3552

Try it with this extension method

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

Upvotes: 1

Related Questions