【发布时间】:2019-08-01 13:41:11
【问题描述】:
我正在尝试将日期和时间的字符串合并为 DateTime 格式,以便我可以得到两个时间戳的差异。
但是当将日期作为“2019 年 7 月 31 日”和时间作为“5:07PM”(在 toDateTimeFormat 方法中可以看到的正确格式)传递给 DateTime 构造函数时,它给了我意外的日期,即 2019- 07-01 17:07:00.000 预计日期应为 2019-07-31 17:07:00.000
我也尝试过使用 DateTime.utc 构造函数但没有成功,下面是我的代码
import 'package:intl/intl.dart';
void main(){
String dateOne = "31-July-2019";
String timeOne = "5:07PM";
String dateTwo = "01-Aug-2019";
String timeTwo = "12:00AM";
DateTime reminderDate = toDateTimeFormat(dateOne,timeOne);
// 2019-07-01 17:07:00.000 which is wrong..., EXPECTED --> 2019-07-31 17:07:00.000
DateTime dueDate = toDateTimeFormat(dateTwo, timeTwo);
bool value = isValidReminderDate(reminderDate, dueDate);
// REMINDER DATE < DUE DATE SO RETURN TRUE ELSE FALSE...., EXPECTED --> TRUE
print(value);
}
var monthsNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
DateTime toDateTimeFormat(String date, String time){
if(date != null && time != null){
//date: 01-jan-2000 and time: "6:45PM"
List<String> _parts = date.split("-");
List<String> _timeParts =[];
var dt = DateFormat("h:mma").parse(time);
_timeParts = DateFormat('HH:mm').format(dt).split(":");
DateTime dateTime = DateTime(int.parse(_parts[2]),monthsNames.indexOf(_parts[1]),int.parse(_parts[0]), int.parse(_timeParts[0]), int.parse(_timeParts[1]) ,);
// ALSO TRIED WITH DateTime.utc(int.parse(_parts[2]),monthsNames.indexOf(_parts[1]),int.parse(_parts[0]), int.parse(_timeParts[0]), int.parse(_timeParts[1]) ,);
// but of no use...
print("dateTime :: $dateTime");
return dateTime;
}
}
bool isValidReminderDate(DateTime reminderDate, DateTime dueDate){
print('isValidReminderDate :: ${reminderDate.difference(dueDate).isNegative}');
return reminderDate.difference(dueDate).isNegative;
}
【问题讨论】: