Dart-如何设置DateTime对象的小时和分钟

Kin*_*ics 8 android dart flutter

如何设置/更改DateTime对象的小时和/或分钟。类似于Date.setHours(..)JavaScript。

如果我做到了

var time = DateTime.parse("2018-08-16T11:00:00.000Z");
Run Code Online (Sandbox Code Playgroud)

我该如何设置小时和分钟 time

A. *_*ski 17

现在有了扩展,你可以做这样的事情

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,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 它用于复制更改字段的旧值:`final newVariable = oldValue.copyWith(year: oldValue.year+1);` (2认同)

spy*_*don 16

从 Dart 2.19.0 开始,该copyWith方法被添加到 中DateTime,可以这样使用:

final currentTime = DateTime.now();
final twelve = currentTime.copyWith(hour: 12, minute: 0);
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 9

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

在讨论中添加了一种update()方法,该方法仅允许修改特定的零件,但看起来并没有实现。

  • 更改日期的另一种方法-time.add(Duration(hours:2,minutes:30)),但我怀疑这是否是解决方案。我不知道另一种更改DateTime的方法 (2认同)

M12*_*123 7

我得到了一个更简单的解决方案:

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

那么来自“formatedDate”的 XX:XX 应该是 00:00

解释:

formatedDate 是一个新的 DateTime 变量,其内容为 newDate 减去小时、分钟......