我正在尝试合并日期和时间的弦乐格式,以便我可以有两个时间戳的差异。
但是,当将日期作为" 2019年7月31日"one_answers" 5:07 pm"(以正确格式((在TodateTimeFormat方法中看到的正确格式(时,它将给我带来意外的日期,即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;
}
您应该能够使用package:intl
直接解析这些字符串(下面有一个警告(。
var dateOne = "31-Jul-2019";
var timeOne = "5:07PM";
var dateTwo = "01-Aug-2019";
var timeTwo = "12:00AM";
var format = DateFormat("dd'-'MMM'-'yyyy hh:mma");
var one = format.parse('$dateOne $timeOne');
var two = format.parse('$dateTwo $timeTwo');
print('$one $two ${two.difference(one)}');
打印2019-07-31 17:07:00.000 2019-08-01 00:00:00.000 6:53:00.000000
警告是您必须使用Jul
而不是July
,而Sep
不是Sept
,因为您在其他地方使用了3个字母缩写。