Javascript 增加时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31383993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript add hours to time
提问by Niels Hermann
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.
我有这个 javascript 代码,它应该显示时间。有用。我不想能够增加额外的时间。假设我想增加 1 小时。
<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?
第一个函数计算我要添加的毫秒数,第二个函数是“实时时钟”。如何将第一个函数实现到第二个函数中,从而得到工作结果?
回答by ben
for adding hours, use setHours
:
要增加小时数,请使用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
参考资料:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
回答by Shrinivas Shukla
Check out this fiddle.
看看这个小提琴。
The constructor Date(milliseconds)
of class Date
can be used here.
构造函数Date(milliseconds)
的class Date
可以在这里使用。
Here is the snippet.
这是片段。
var now = new Date();
alert(now);
var milliseconds = new Date().getTime() + (1 * 60 * 60 * 1000);
var later = new Date(milliseconds);
alert(later);
回答by brijTechGeek
Check out this
fiddle here
var todayDate = new Date();
alert("After adding ONE hour : "+new Date(todayDate.setHours(todayDate.getHours()+1)) );