Javascript Date/Time not Working on iOS Device with Chrome

1.7k Views Asked by At

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)
{
2

There are 2 best solutions below

3
atymic On

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/

1
Vlad Maican On

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)