添加时间到Javascript Date对象? [英] Adding hours to Javascript Date object?
问题描述
令我感到奇怪的是,Javascript的Date对象并没有实现任何类型的添加功能。
我只想要一个可以做到这一点的功能:
var now = Date.now();
var fourHoursLater = now.addHours(4);
函数Date.prototype.addHours(h){
//如何实现?
}
我只是想方向一些指针。 p>
-
我需要做字符串解析吗?
-
我可以使用setTime吗?
-
/ li>
像这样:
new日期(毫秒+ 4 * 3600 * 1000 / * 4小时毫秒* /)?
这似乎真的很骇人听闻 - 甚至还能工作吗?
JavaScript本身具有可怕的Date / Time API。这是纯粹的JavaScript中唯一的方法。我建议使用 Datejs (如Nosredna所建议的),如果您正在做很多日期操作,但是。
Date.prototype.addHours = function(h){
this.setTime(this.getTime()+ (h * 60 * 60 * 1000));
返回这个;
}
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?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /*4 hrs in ms*/)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. This is the only way to do it in pure JavaScript. I'd recommend using Datejs - as suggested by Nosredna - if you're doing a lot of date manipulation, though.
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
这篇关于添加时间到Javascript Date对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!