Aby uzyskać prostą funkcję dodawania / odejmowania godziny / minuty w javascript, spróbuj tego:
function getTime (addHour, addMin){
addHour = (addHour?addHour:0);
addMin = (addMin?addMin:0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
//change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12?true:false);
}else{
hours = time.getHours();
AM = (hours>=12?false:true);
}
//get the current minutes
var minutes = time.getMinutes();
// set minute
if((minutes+addMin) >= 60 || (minutes+addMin)<0){
overMin = (minutes+addMin)%60;
overHour = Math.floor((minutes+addMin-Math.abs(overMin))/60);
if(overMin<0){
overMin = overMin+60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10?'0':'')+overMin);
addHour = addHour+overHour;
}else{
newMin = minutes+addMin;
newMin = String((newMin<10?'0':'')+newMin);
}
//set hour
if(( hours+addHour>=13 )||( hours+addHour<=0 )){
overHour = (hours+addHour)%12;
ndble = Math.floor(Math.abs((hours+addHour)/12));
if(overHour<=0){
newHour = overHour+12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour ==0 ){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10?'0':'')+String(newHour);
AM = ((ndble+1)%2===0)?AM:!AM;
}else{
AM = (hours+addHour==12?!AM:AM);
newHour = String((Number(hours)+addHour<10?'0':'')+(hours+addHour));
}
var am = (AM)?'AM':'PM';
return new Array(newHour, newMin, am);
};
Można tego użyć bez parametrów, aby uzyskać bieżący czas
getTime();
lub z parametrami, aby uzyskać czas z dodanymi minutami / godzinami
getTime(1,30); // adds 1.5 hours to current time
getTime(2); // adds 2 hours to current time
getTime(0,120); // same as above
działa nawet czas ujemny
getTime(-1, -30); // subtracts 1.5 hours from current time
ta funkcja zwraca tablicę
array([Hour], [Minute], [Meridian])