flutter - 从 DateTime 类中获取意外日期

标签 flutter dart

我正在尝试将日期和时间的字符串合并为 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;
}

最佳答案

您应该能够使用 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 而不是 JulySep 而不是 Sept 因为您使用的是别处的 3 个字母缩写。

关于flutter - 从 DateTime 类中获取意外日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57310411/

相关文章:

flutter - 如何在列内添加包装 future builder

flutter - 如何捕捉 "Unable to load asset: assets/images/sample_img_url.png"

dart - 无法扫描文本文件的内容

flutter - 如何在 flutter 右侧的 RadioButtonList Tile 中设置单选按钮

flutter - 如何在Flutter上设置tflite PoseNet “Single-Person Pose Estimation”?

flutter - 如何检测 Flutter 应用程序何时从后台返回?

pdf - 我想从PDF文件中获取总页数

flutter - Flutter sqflite,从rawQuery检索数据

javascript - Dart2Js 但可读

dart - 为什么在Dart中使用StringBuffer而不是Iterable.join?