Tuesday, May 7, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  149] [ 7]  / answers: 1 / hits: 30765  / 9 Years ago, mon, july 13, 2015, 12:00:00

I have this javascript code which should show the time. It works. I wan't to be able to add extra time though. Lets say that I want to add 1 hour.



        <script type=text/javascript>
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
// This function gets the current time and injects it into the DOM

function updateClock() {
// Gets the current time
var now = new Date();

// Get the hours, minutes and seconds from the current time
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();

// Format hours, minutes and seconds
if (hours < 10) {
hours = 0 + hours;
}
if (minutes < 10) {
minutes = 0 + minutes;
}
if (seconds < 10) {
seconds = 0 + seconds;
}

// Gets the element we want to inject the clock into
var elem = document.getElementById('clock');

// Sets the elements inner HTML value to our clock data
elem.innerHTML = hours + ':' + minutes + ':' + seconds;
}
function start(){
setInterval('updateClock()', 200);
}
</script>


The first function calculates the milisecons that I want to add, and the second function is the live clock. How do I implement the first function into the second one, so I get the working result?


More From » time

 Answers
47

for adding hours, use setHours :





// Gets the current time
var now = new Date();

console.log(actual time:, now);

now.setHours(now.getHours() + 1)

console.log(actual time + 1 hour:, now);





For references: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours


[#65827] Friday, July 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jameson

Total Points: 534
Total Questions: 103
Total Answers: 102

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;