Javascript会增加时间
Javascript add hours to time
我有这个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>
第一个函数计算我想要添加的毫秒数,第二个函数是"实时时钟"。我如何实现第一个函数到第二个,所以我得到工作结果?
添加小时数,使用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);
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
看看这个小提琴
此处可以使用class Date
的构造函数Date(milliseconds)
下面是代码片段。
var now = new Date();
alert(now);
var milliseconds = new Date().getTime() + (1 * 60 * 60 * 1000);
var later = new Date(milliseconds);
alert(later);
看看这个
此处提琴
var todayDate = new Date();
alert("After adding ONE hour : "+new Date(todayDate.setHours(todayDate.getHours()+1)) );
javascript日期API即将完成,它的现有方法可以用来为这个API添加另一个功能,有人说这是繁琐的,但它不是。
为了在日期中添加方法,我们将访问该API的原型
。
Date.prototype.addTime = function(str){
function parse(str){
let arr = (typeof str == 'number')?[str]:str.split(":").map(t=>t.trim());
arr[0] = arr[0] || 0;
arr[1] = arr[1] || 0;
arr[2] = arr[2] || 0;
return arr
}
function arrToMill(arr){
let [h,m,s] = arr;
return (h*60*60*1000) + (m*60*1000) + (s*1000);
}
let date = new Date(this.getTime());
let parsed = parse(str);
date.setTime(date.getTime() + arrToMill(parsed));
return date;
}
让它摇滚起来。这个函数是不可变的
let date = new Date();
date.addTime(1);
date.addTime("01:00");`
相关文章:
- 如何每10.6秒从时间戳增加+1
- JavaScript到PHP的时间戳失败,增加了大约一个半月的时间
- 引导时间选择器在增加或减少小时和分钟的同时获取 NaN
- 日期时间格式增加了一个小时
- 在时间间隔后增加数据库中的值
- 当使用日期时间选择器格式时,它每年增加5
- 增加在选择元素HTML中搜索的时间
- 需要在EXTJ的时间字段中显示07:00、15:00、23:00(增加8小时)
- 增加营业时间到coutdown计数器
- 如何增加“Chrome 推送通知”的可见性时间
- Firebase limitToLast() 是否会随着孩子的记录计数增加而增加更长的时间
- 比较前将时间增加一小时
- 当从客户端从ajax调用检索时,我在服务器上的日期时间增加了12.30小时
- 如何在javascript游戏中随着时间的推移增加产卵率
- 可以缓存JSON以增加性能/加载时间
- 按时间增加数字
- Ajax调用增加了网站加载时间
- JS搜索通过一个嵌套的JSON结构,深度增加随着时间的推移
- setUTCHours将传递给函数的时间增加一个小时
- 如何在之前“更改”的结束时间增加2小时开始,使用jQuery时间选择器