Dart - How to set the hour and minute of DateTime object
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.
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,
);
}
}
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
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');