Skip to main content
16-Pearl
August 25, 2022
Solved

Unable to get the difference between two dates and times

  • August 25, 2022
  • 2 replies
  • 1855 views

Hi, community,

 

I have been spinning my wheels with getting the differenthe ce between two dates and time.

The aim is to find the duration between the time a device is turned off and when that device is turned on.

 

I have two different services that output a datetime value. One service outputs the time the device is turned on and the second service outputs the time the device is switched off.

I then created a third service that calculates the difference between the two times.

 

Below is what I wrote in my third service:

var date1 = parseDate(onTimes_Input, " dd-MMM-YYYY HH:mm");
var date2 = parseDate(offTimes_Input, " dd-MMM-YYYY HH:mm");
let result= dateDifference(onTimes, offTimes);

 

when I execute the above, I get the following error: 

Error executing service getDuration. Message :: Invalid format: "1661387400000" - See Script Error Log for more details.

 

 

Does anyone know what this could mean?

Best Regards

Jay_nisaa 🙂

Best answer by Sathishkumar_C

 

Try below code to get a difference between 2 datetime values. If parsing not required, then directly use here.

 

result = Math.abs(date1 - date2)/(1000 * 60); //In Minutes

 

 

 

2 replies

12-Amethyst
August 25, 2022

Hi @Janicen,

 

Did you try running the dateDifference service directly with onTimes_Input and offTimes_Input?  If the result of the services that provides these values is DATETIME the value is already in milliseconds and does not need to be parsed.

 

Thanks,

 

Travis

17-Peridot
August 25, 2022

 

Try below code to get a difference between 2 datetime values. If parsing not required, then directly use here.

 

result = Math.abs(date1 - date2)/(1000 * 60); //In Minutes

 

 

 

Janicen16-PearlAuthor
16-Pearl
August 26, 2022

thank you very much. This was helpful.

 

1. Additionally, I did a few things I want to share.

To convert the minutes to hours:

      var x = Math.abs(date1 - date2)/(1000 * 60); 

      var inHours = x/60;

 

2. To get the time difference to display in hours and minutes (e.g., 12 hours 30 minutes):

         var hours = parseInt(x/60); ///get the absolute value of the hours without minutes (inHours).

         var minutes = Math.floor((inHours- hours)*60); ///get the absolute value of the minutes.

         

         let result = hours + "h"+minutes ///concatenate the hours and minute.

 

Best Regards