首页 > 解决方案 > Flutter:从两个不同的变量中添加日期和时间以转换为 UTC

问题描述

我想合并这两个日期和时间变量,并有另一个名为var toUTC.

Date Picker我有两个来自and的日期和时间变量Time Picker

var selectedDate;
var selectedTime;

print(selectedDate); // 2021-02-06 00:00:00.000
print(selectedTime); // 1:15:00.000000

var selectedDate时间,但我不想用这个。我想用来自的值替换它var selectedTime

我想做的是

print(toUTC) // 2021-02-06 1:15:00.00000 <---- merge selectedDate and selectedTime

转换为UTC时间。

我试图只接受2021-02-06并与 合并selectedTime,但我未能转换为UTC.

标签: flutterdart

解决方案


final toUTC = DateTime(selectedDate.year, selectedDate.month, selectedDate.year, 
selectedTime.hour, selectedTime.minute);

或者,如果您需要定期执行某些操作,则可以对其进行扩展。下面通过将小时和分钟作为单独的变量传递来做到这一点,但如果您愿意,可以将其更改为另一个 DateTime 值。

extension DateTimeExtensions on DateTime {

 /// Creates a new date time with the given date but with the time
 /// specified from [time]
 DateTime withTime([int hour = 0, int minute = 0]) =>
     DateTime(this.year, this.month, this.day, hour, minute);

}

要转换为 UTC,可以在 DateTime 类上使用 toUtc() 方法。我不确定您是否只是没有发现,或者是否有我没有看到的问题?


推荐阅读