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!
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.
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.
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));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With