向 JavaScript Date 对象添加小时数? [英] Adding hours to JavaScript Date object?
本文介绍了向 JavaScript Date 对象添加小时数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
令我惊讶的是 JavaScript 的 Date 对象没有实现任何类型的添加功能.
It amazes me that JavaScript's Date object does not implement an add function of any kind.
我只是想要一个可以做到这一点的函数:
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// how do I implement this?
}
我只是想要一些指向某个方向的指针.
I would simply like some pointers in a direction.
我需要做字符串解析吗?
Do I need to do string parsing?
我可以使用 setTime 吗?
Can I use setTime?
毫秒呢?
像这样:
new Date(milliseconds + 4*3600*1000 /*4 hrs in ms*/)?
虽然这看起来很hackish - 它甚至有效吗?
This seems really hackish though - and does it even work?
推荐答案
JavaScript 本身有糟糕的日期/时间 API.尽管如此,您可以在纯 JavaScript 中执行此操作:
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
这篇关于向 JavaScript Date 对象添加小时数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文