Kingsley CA
Kingsley CA

Reputation: 11614

Dart - How to set the hour and minute of DateTime object

How do I set/change the hour and/or minute of a DateTime object. Similar to Date.setHours(..) in JavaScript.

e.g If i did

var time = DateTime.parse("2018-08-16T11:00:00.000Z");

how do I set the hour and minute of time

Upvotes: 50

Views: 69832

Answers (9)

spydon
spydon

Reputation: 11512

Since Dart 2.19.0 the copyWith method was added to DateTime, it can be used like this:

final currentTime = DateTime.now();
final twelve = currentTime.copyWith(hour: 12, minute: 0);

Upvotes: 25

Jama Mohamed
Jama Mohamed

Reputation: 3405

You can also do this by adding or subtracting to DateTime, using this package Jiffy. It also respects leap years and how many days are in each month

var updateTime = Jiffy.parse("2018-08-16T11:00:00.000Z").add(hours: 1); // 2018-08-16 12:00:00.000Z

print(updateTime.dateTime); // 2018-08-16 12:30:00.000Z

// also you can format it
print(updateTime.format("yyyy, MMM")); // 2018, Aug

// or use default formats
print(updateTime.yMMMEdjm); // Thu, Aug 16, 2018 12:30 PM

Upvotes: 0

Adam Smaka
Adam Smaka

Reputation: 6393

You can use Extension Methods with dart to extend existing libraries.

First define your extension , by extending the DateTime Object:

extension DateTimeExt on DateTime {
  DateTime applyTimeOfDay({required int hour, required int minute}) {
      return DateTime(year, month, day, hour, minute);
}
}

Once your new method is defined, you can call it exactly like the already defined methods of that object.

in this case, once you defined the applyTimeOfDay() method you can call it like so :

int myNewHour = 10
int myNewMinute = 8
var time = DateTime.parse("2018-08-16T11:00:00.000Z");
time = time.applyTimeOfDay(hour : myNewHour, minute : myNewMinute);

Upvotes: 4

spydon
spydon

Reputation: 11512

You can remove the current hours and minutes, and then add your wanted hours and minutes.

So if you would want to set the time to for example 23:59 you could do this:

    final date = DateTime.now();
    date
      ..subtract(Duration(hours: date.hour, minutes: date.minute))
      ..add(Duration(hours: 23, minutes: 59));

(Note that the other time units like seconds and milliseconds aren't changed here)

Upvotes: 2

I had some issues while using the formatted form of a DateTime object (using DateFormat) in my widget because showDatePicker brought a new instance of DateTime and calling setState doesn't have effect on the view.

There might be better ways to comply with my problem, but I decided to create my own one which is updateable using .update method.

import 'package:flutter/material.dart';

class MDateTime {
  int year, month, day, hour, min, sec;

  factory MDateTime.fromDateTime(DateTime dateTime) {
    return MDateTime(
      dateTime.year,
      dateTime.month,
      dateTime.day,
      dateTime.hour,
      dateTime.minute,
      dateTime.second,
    );
  }

  MDateTime([
    this.year = 0,
    this.month = 0,
    this.day = 0,
    this.hour = 0,
    this.min = 0,
    this.sec = 0,
  ]);

  void update({
    int? newYear,
    int? newMonth,
    int? newDay,
    int? newHour,
    int? newMin,
    int? newSec,
  }) {
    year = newYear ?? year;
    month = newMonth ?? month;
    day = newDay ?? day;
    hour = newHour ?? hour;
    min = newMin ?? min;
    sec = newSec ?? sec;
  }

  DateTime toDateTime() {
    return DateTime(year, month, day, hour, min, sec);
  }

  TimeOfDay toTimeOfDay() {
    return TimeOfDay(hour :hour, minute:  min);
  }

  String formatDate({String divider = "-"}){
    return "$year$divider$month$divider$day";
  }

  String formatTime({String divider = ":"}){
    return "$hour$divider$min$divider$sec";
  }
}

Moreover, there is no need to use another package for date-time formatting.

Upvotes: 0

A. Tratseuski
A. Tratseuski

Reputation: 691

now with extension u could do something like this

extension MyDateUtils on DateTime {
  DateTime copyWith({
    int? year,
    int? month,
    int? day,
    int? hour,
    int? minute,
    int? second,
    int? millisecond,
    int? microsecond,
  }) {
    return DateTime(
      year ?? this.year,
      month ?? this.month,
      day ?? this.day,
      hour ?? this.hour,
      minute ?? this.minute,
      second ?? this.second,
      millisecond ?? this.millisecond,
      microsecond ?? this.microsecond,
    );
  }
}

Upvotes: 42

m123
m123

Reputation: 3152

I got a simpler solution:

DateTime newDate = DateTime.now();
DateTime formatedDate = newDate.subtract(Duration(hours: newDate.hour, minutes: newDate.minute, seconds: newDate.second, milliseconds: newDate.millisecond, microseconds: newDate.microsecond));

Then the XX:XX from 'formatedDate' should be 00:00

Explanation:

formatedDate is a new DateTime variable with the content of newDate minus hours, minutes... from it

Upvotes: 12

Jamie O'Toole
Jamie O'Toole

Reputation: 31

I believe this is a better solution than the accepted answer:

DateTime dateTime = DateFormat('dd-MM-yyyy h:mm:ssa', 'en_US').parseLoose('01-11-2020 2:00:00AM');

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657058

var newHour = 5;
time = time.toLocal();
time = new DateTime(time.year, time.month, time.day, newHour, time.minute, time.second, time.millisecond, time.microsecond);

There were discussions to add an update() method that allows to modify specific parts only, but it doesn't look like this has landed.

Upvotes: 82

Related Questions