Puzzling Date/Time Difference in Javascript

Hi there,

I have this pretty frustrating time with my date arithmetic operation. I have 4 fields Date1, Time1, Date2, Time2. The reason i split them is for user friendliness purpose. What I wanted to achieve was to find the difference in minutes i.e (Date2/Time2) - (Date1/Time1). I have also changed the date format of the Date1 and Date2 fields to have it shown January 25,2007, as I found that having the conventional format of 25/01/2007, would just not work, wonder why? To test the functionality I’ve put the following javascript in a button. The script works fine if e.g 25/01/2007 11:42AM - 25/01/2007 11:40AM, it returns 2 minutes.

Problem arises when I input the following dates 25/01/2007 12:10PM - 25/01/2007 11:40AM. I’m expecting it to return 30 minutes but instead the value retured is 750. This is because the 25/01/2007 12:10PM is interpreted as 26/01/2007 12:10AM. Why is like this…

var doc;

doc = window.document.forms[0];

var minutes = 0;

var days = 0;

var minutes = 0;

var difference = 0;

var d1 = new Date(doc.Date1.value + " " + doc.Time1.value)

var d2 = new Date(doc.Date2.value + " " + doc.Time2.value)

newd1 = new Date(d1);

newd2 = new Date(d2);

difference = newd2 - newd1;

minutes = Math.round(difference/(1000*60));

alert("Date/time1: " + newd1);

alert("Date/time2: " + newd2);

alert(minutes);

Please help…

Subject: Puzzling Date/Time Difference in Javascript

Can you check when you are making a Datetime Object from the Individual Date and Time part returing the expected datetime.

Since the actual syntax for a new Datetime Object is something like:

new Date(year, month, day, hours, minutes, seconds, milliseconds)

Subject: RE: Puzzling Date/Time Difference in Javascript

Hi there,

If I change the time format to 24hour format, then my script works fine. I suppose javascript could not differentiate the AM/PM symbol when I use 12 hour system ?

Here’s the result of my experiment:

Sampled date: 25/01/2007 12:45 PM

var d1 = new Date(doc.Date1.value + " " + doc.Time1.value)

newd1 = new Date(d1);

alert(newdt1);

Using 12hour time format, the result is:

Fri Jan 26 00:45:00 GMT+0800 (Malay Peninsula Standard Time) 2007.

Using 24hour time format, the result is:

Thu Jan 25 12:45:00 GMT+0800 (Malay Peninsula Standard Time) 2007.

As you can see the result displayed using the 12hour format is wrong, it becomes 26/01/2007 12:45 AM. How could I avoid this without having to change to 24hour format. My customer would not favour that.

Cheer and thanks.