0

I am trying to get the time difference of two time values , one coming from a json object in the format of

DateFormat('dd-MM-yyyy HH:mm:ss')

and the other is from

DateTime.now()

. Since DateTime.now() is coming in this format "2020-06-23 08:10:36.411419" including the microseconds.

In which case I cannot get the difference of these two time values because value coming from json has no microseconds.

So I have to format the DateTime.now() value to match the json value.(cleaningStartTime is the value coming from json)

So I wrote this code

var formatTime =  DateFormat('yyyy-MM-dd HH:mm:ss');
  var timeNow = formatTime.format(DateTime.now());
  var diff = timeNow.difference(cleaningStartTime);

code from Android studio

But when i try to return the "diff" value it gives me this error.

The method 'difference' isn't defined for the class 'String'. Try correcting the name to the name of an existing method, or defining a method named 'difference'. var diff = timeNow.difference(cleaningStartTime);

How do I approach to fix this issue ?

flutter version = v1.17.1

  • 2
    `DateTime.difference` computes the difference between two `DateTime` objects, but you're trying to call it on a `String`. Just use `DateTime.now().difference(cleaningStartTime)`. Just because one of the times doesn't have microseconds doesn't prevent you from computing the time difference. – jamesdlin Jun 23 '20 at 03:37
  • HI jamedin. Thanks for the reply. I tried that way but it gives this error. "type 'String' is not a subtype of type 'DateTime'" var diff = DateTime.now().difference(cleaningStartTime); – Sameera Tennakoon Jun 23 '20 at 03:43
  • 1
    Then `cleaningStartTime` is also not a `DateTime` object. You would need to use `DateFormat.parse` ([or something similar](https://stackoverflow.com/a/61394854/179715)) to convert it to a `DateTime` object first. – jamesdlin Jun 23 '20 at 03:46

0 Answers0