Community Tip - Want the oppurtunity to discuss enhancements to PTC products? Join a working group! X
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
Solved! Go to Solution.
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
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
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
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