如何将flutter TimeOfDay转换为DateTime?

Rob*_*nha 9 dart flutter

我有时间选择器返回TimeOfDay对象,但我已将该值保存在数据库中,作为从DateTime.millisecondsSinceEpoch获得的毫秒整数

Rém*_*let 18

这是不可能的. TimeOfDay持有小时和分钟.虽然也有日/月/年DateTime

如果要转换它,则需要更多信息.比如当前的DateTime.然后将两者合并为一个最终日期时间.

TimeOfDay t;
final now = new DateTime.now();
return new DateTime(now.year, now.month, now.day, t.hour, t.minute);
Run Code Online (Sandbox Code Playgroud)

  • 只是个小技巧,您可以在此代码的一行中完成此操作,只需执行以下操作:return DateTime.now()。add(Duration(hours:t.hour,minutes:t.minute)); (2认同)
  • 不,您可以将小时和分钟添加到dateTime.now() (2认同)

Ada*_*aka 8

您可以使用 DateTime 扩展

extension DateTimeExtension on DateTime {
  DateTime applied(TimeOfDay time) {
    return DateTime(year, month, day, time.hour, time.minute);
  }
}
Run Code Online (Sandbox Code Playgroud)

那么你可以像这样使用它:

final dateTime = yourDate.applied(yourTimeOfDayValue);

并将 pubspec.yaml 中的 sdk 版本更改为

environment:
 sdk: ">=2.7.0 <3.0.0"
Run Code Online (Sandbox Code Playgroud)


Cod*_*ner 6

您可以像这样使用 entension,也可以在单独的文件(如 dateTime_extensions.dart)中添加更多扩展方法,以使您的工作在未来的项目中也变得轻松

文件:dateTime_extensions.dart;


extension DateTimeExtension on DateTime {
DateTime setTimeOfDay(TimeOfDay time) {
    return DateTime(this.year, this.month, this.day, time.hour, time.minute);
  }

  DateTime setTime(
      {int hours = 0,
      int minutes = 0,
      int seconds = 0,
      int milliSeconds = 0,
      int microSeconds = 0}) {
    return DateTime(this.year, this.month, this.day, hours, minutes, seconds,
        milliSeconds, microSeconds);
  }

  DateTime clearTime() {
    return DateTime(this.year, this.month, this.day, 0, 0, 0, 0, 0);
  }

   ///..... add more methods/properties for your convenience 
}

Run Code Online (Sandbox Code Playgroud)

像这样使用它


import 'package:your_app/dateTime_extensions.dart';

    date.clearTime(); //to clear timeSpan
    date.setTime(); //also be used to clear time if you don't provide any parameters
    date.setTime(hours: 16,minutes: 23,seconds: 24); // will set time to existing date eg. existing_date 16:23:24
    date.setTimeOfDay(TimeOfDay(hour: 16, minute: 59));

Run Code Online (Sandbox Code Playgroud)