3

I am working with date/time in javascript and it is working properly on chrome windows but it is not working within Chrome on iOS devices. The difference between two times is not calculated properly on iOS.

Here is my code:

var start_timeObj = moment(start_time, ["h:mm A"]);
var end_timeObj = moment(end_time, ["h:mm A"]);
var start_time=start_timeObj.format("HH:mm");
var end_time=end_timeObj.format("HH:mm"); 

var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;

if(diff==1)
{
user3653474
  • 3,393
  • 6
  • 49
  • 135
  • `new Date("1970-1-1 " + end_time)` is not a format supported by ECMA-262, so parsing is implementation dependent. Why do you use moment.js to parse one string, but the built–in parser for another? Just make one string and use moment.js to parse it. Avoid the built–in parser, always.. – RobG Jul 26 '19 at 20:22

2 Answers2

0

Have you tried using moment's built in diff functionality?

var start = moment(start_time, ["h:mm A"]);
var end = moment(end_time, ["h:mm A"]);
var diffMilliseconds = end.diff(start) // outputs 3600000 (in ms)
var diffHours = diff / 1000 / 60 / 60; // outputs 1

Documentation: https://momentjs.com/docs/#/displaying/difference/

atymic
  • 3,093
  • 1
  • 13
  • 26
0

If you don't want to use moment you could try using:

var date1 = new Date('1998-07-20');
var date2 = new Date('1998-07-23');
var diffTime = Math.abs(date2.getTime() - date1.getTime());
diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1; 

If you don't add 1 to diffDays the end date won't be included.

You can do exactly the same using a H:m:s format (https://playcode.io/396986?tabs=script.js,preview,console)

  • The OP is trying to determine if the difference between two times in hours, not days between dates. – RobG Jul 26 '19 at 20:24