Home > Back-end >  How to get time difference in Flutter?
How to get time difference in Flutter?

Time:10-13

I have current time data and future time data which I get in nexTime variable and convert it to date. I need to subtract the current time from tempDate (future time), I do it through the subtract method, but I run into a problem that the result is 1970. Tell me, how can I subtract the current time from the future time to get the difference?

      var timeNowMS = (DateTime.now()).millisecondsSinceEpoch;
      var timenowSeconds = (timeNowMS / 1000).round();
      DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm").parse(
          "${timeNow.year}-${timeNow.month}-${timeNow.day} ${nexTime as String}");
      final Duration timeNowDuration = Duration(seconds: timenowSeconds);
      final DateTime drive = tempDate.subtract(timeNowDuration);

drive result

enter image description here

tempDate

enter image description here

timeNowDuration

enter image description here

CodePudding user response:

there is a method that calculates Duration from two dates an example :

DateTime date1 = /* your first date */
DateTime date2 = /* your other date */

Duration diff = date2.now().difference(date1);

it will generate a Duration with the duration between the two dates

and If you want to get a DateTime after adding a Duration to a previous date, use :

    DateTime dateAfterAddinOneDay = DateTime.now().add(Duration(days: 1));

so as today is 2022-10-12, the dateAfterAddinOneDay will be 2022-10-13

  • Related