Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding 30 minutes to Date causes it to go back 30 minutes

I have a Javascript Date object equal to 00:30 and when doing:

date.setMinutes(date.getMinutes() + 30);

causes the date object to equal 00:00.

Does anyone know why this is happening?

Here is where the code is being used:

for (var i = openTime; i <= closeTime; i.setMinutes(i.getMinutes() + timeIncrement)) {
  var time = i.getHours() + (i.getHours() == 0 ? '0' : '') + ':' + i.getMinutes() + (i.getMinutes() == 3 || i.getMinutes() == 0 ? '0' : '');

  $(timeClientId).append($('<option />').val(time).text(time));
} 

The above script creates a list of times available from 10:00am all the way to 02:00am the next day.

It runs fine until it reaches midnight 00:00 after many successful iterations.

Can anyone help?

Thanks!

ANSWER/SOLUTION:

This problem was due to a daylight saving issue, so this Saturday the clocks go forward. For some odd reason when adding 30 minutes to 12:30 it reset back to 12:00 using .setMinutes(). This kept it in an endless loop. The solution was to add minutes using i.setTime(i.getTime() + timeIncrement * 60 * 1000) This sorted the issue.

Cheers for all your answers!

like image 329
Base33 Avatar asked Mar 22 '12 10:03

Base33


People also ask

How do you add minutes to a Date?

To add the number of minutes into the Date object using the setMinutes() method first we get the value of minutes of the current time using the getMinutes( ) method and then add the desired number of minutes into it and pass the added value to the setMinutes( ) method.

How can I write current time in JavaScript?

In JavaScript, we can easily get the current date or time by using the new Date() object. By default, it uses our browser's time zone and displays the date as a full text string, such as "Fri Jun 17 2022 10:54:59 GMT+0100 (British Summer Time)" that contains the current date, time, and time zone.


2 Answers

You are only setting the minutes. So of course 30 minutes + 30 minutes on the clock equals 60 minutes, i.e. 0 minutes.

Use this clever method (it's clever because it works with all rollovers!):

function addMinutes(inDate, inMinutes)
{
    var newdate = new Date();
    newdate.setTime(inDate.getTime() + inMinutes * 60000);
    return newdate;
}

var date = new Date();

alert(addMinutes(date,-30));​
like image 67
Karlth Avatar answered Sep 26 '22 01:09

Karlth


How are you initialising your date? setMinutes seems to work as expected so perhaps there is an error in your initial value. See below for my quick n dirty test.

var date = new Date(0);
document.write(date);
document.write("<br>");
date.setMinutes(30);
document.write(date);
document.write("<br>");
date.setMinutes(date.getMinutes() + 30);
document.write(date);
document.write("<br>");

Outputs:

Thu Jan 1 00:00:00 UTC 1970
Thu Jan 1 00:30:00 UTC 1970
Thu Jan 1 01:00:00 UTC 1970
like image 34
Max Avatar answered Sep 23 '22 01:09

Max