我想获得一个日期对象,它比另一个日期对象晚30分钟。我如何用JavaScript做到这一点?
当前回答
使用图书馆
如果您正在做大量的日期工作,您可能需要查看JavaScript日期库,如Datejs或Moment.js。例如,在Moment.js中,这很简单:
var newDateObj = moment(oldDateObj).add(30, 'm').toDate();
香草Javascript
这就像是混沌的答案,但只有一句话:
var newDateObj = new Date(oldDateObj.getTime() + diff*60000);
其中diff是您希望与oldDateObj的时间之间的分钟差值。甚至可以是负的。
或者作为一个可重用的函数,如果你需要在多个地方这样做:
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
为了防止这不是很明显,我们用分钟乘以60000的原因是为了把分钟转换成毫秒。
小心香草Javascript。约会很难!
你可能认为你可以把一个约会增加24小时来得到明天的约会,对吗?错了!
addMinutes(myDate, 60*24); //DO NOT DO THIS
事实证明,如果用户使用日光节约时间,一天并不一定是24小时。每年有一天只有23个小时,而每年有一天只有25个小时。例如,在美国和加拿大的大部分地区,2014年11月2日午夜后24小时仍然是11月2日:
const NOV = 10; //because JS months are off by one...
addMinutes(new Date(2014, NOV, 2), 60*24); //In USA, prints 11pm on Nov 2, not 12am Nov 3!
这就是为什么如果您必须在此方面做大量工作,使用上述库之一是更安全的选择。
下面是我编写的这个函数的一个更通用的版本。我仍然建议使用库,但这对你的项目来说可能是多余的/不可能的。语法模仿MySQL的DATE_ADD函数。
/**
* Adds time to a date. Modelled after MySQL DATE_ADD function.
* Example: dateAdd(new Date(), 'minute', 30) //returns 30 minutes from now.
* https://stackoverflow.com/a/1214753/18511
*
* @param date Date to start with
* @param interval One of: year, quarter, month, week, day, hour, minute, second
* @param units Number of units of the given interval to add.
*/
function dateAdd(date, interval, units) {
if(!(date instanceof Date))
return undefined;
var ret = new Date(date); //don't change original date
var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);};
switch(String(interval).toLowerCase()) {
case 'year' : ret.setFullYear(ret.getFullYear() + units); checkRollover(); break;
case 'quarter': ret.setMonth(ret.getMonth() + 3*units); checkRollover(); break;
case 'month' : ret.setMonth(ret.getMonth() + units); checkRollover(); break;
case 'week' : ret.setDate(ret.getDate() + 7*units); break;
case 'day' : ret.setDate(ret.getDate() + units); break;
case 'hour' : ret.setTime(ret.getTime() + units*3600000); break;
case 'minute' : ret.setTime(ret.getTime() + units*60000); break;
case 'second' : ret.setTime(ret.getTime() + units*1000); break;
default : ret = undefined; break;
}
return ret;
}
工作的jsFiddle演示。
其他回答
这就是我所做的,似乎很有效:
Date.prototype.addMinutes = function(minutes) {
var copiedDate = new Date(this.getTime());
return new Date(copiedDate.getTime() + minutes * 60000);
}
然后你可以这样调用它:
var now = new Date();
console.log(now.addMinutes(50));
我总是创建7个函数,在JS中使用date: addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears。
你可以在这里看到一个例子:http://jsfiddle.net/tiagoajacobi/YHA8x/
使用方法:
var now = new Date();
console.log(now.addMinutes(30));
console.log(now.addWeeks(3));
这些是函数:
Date.prototype.addSeconds = function(seconds) {
this.setSeconds(this.getSeconds() + seconds);
return this;
};
Date.prototype.addMinutes = function(minutes) {
this.setMinutes(this.getMinutes() + minutes);
return this;
};
Date.prototype.addHours = function(hours) {
this.setHours(this.getHours() + hours);
return this;
};
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
Date.prototype.addWeeks = function(weeks) {
this.addDays(weeks*7);
return this;
};
Date.prototype.addMonths = function (months) {
var dt = this.getDate();
this.setMonth(this.getMonth() + months);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
Date.prototype.addYears = function(years) {
var dt = this.getDate();
this.setFullYear(this.getFullYear() + years);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
var myDate= new Date();
var MyNewDate = new Date
(myDate.getFullYear(),myDate.getMonth(),myDate.getDate(),myDate.getMinutes()+10,01,01)
停止使用Moment.js
正如其他优秀答案所建议的那样,在大多数情况下,处理日期时最好使用库。然而,重要的是要知道,自2020年9月起,Moment.js被认为是遗留的,不应再用于新项目。
引用Moment在官方文件中的声明:
我们不希望在未来的新项目中使用Moment。[…我们现在通常认为Moment是一个处于维护模式的遗留项目。它还没死,但已经完成了。
现代图书馆
以下是Moment推荐的替代方案。
勒克桑
《Luxon》可以看作是《Moment》的演变。作者Isaac Cambron是Moment的长期贡献者。请阅读卢克松为什么存在?以及Luxon文档中的For Moment用户页面。
locale:提供的Intl 时区:提供国际时区
import {DateTime} from 'luxon'
function addMinutes(date, minutes) {
return DateTime.fromJSDate(date).plus({minutes}).toJSDate()
}
Day.js
Day.js被设计成一个极简的Moment.js替代品,使用类似的API。它不是一个临时的替代品,但如果你习惯了使用Moment的API,想要快速移动,可以考虑使用Day.js。
区域设置:可以单独导入的自定义数据文件 时区:国际提供,通过一个插件
import dayjs from 'dayjs'
function addMinutes(date, minutes) {
return dayjs(date).add(minutes, 'minutes').toDate()
}
日期-fns
Date-fns提供了一系列用于操作JavaScript Date对象的函数。要了解更多详细信息,请滚动到date-fns主页上的“为什么是date-fns?”
区域设置:可以单独导入的自定义数据文件 时区:通过单独的配套库提供了Intl
import {addMinutes} from 'date-fns'
function addMinutesDemo(date, minutes) {
return addMinutes(date, minutes)
}
js-Joda
js-Joda是Java的Three-Ten Backport的JavaScript端口,它是Java SE 8 Java的JSR-310实现的基础。包的时间。如果你熟悉java。time, joda time,或Noda time,你会发现js-Joda相当。
区域:通过附加模块自定义数据文件 时区:通过附加模块自定义数据文件
import {LocalDateTime, nativeJs, convert} from '@js-joda/core'
function addMinutes(date, minutes) {
return convert(
LocalDateTime.from(
nativeJs(date)
).plusMinutes(minutes)
).toDate()
}
var now = new Date(); now.setMinutes(now.getMinutes() + 30);/ /时间戳 日期(现在);//日期对象 console.log(现在);