我想得到一个比另一个 Date 对象晚 30 分钟的 Date 对象。我如何用 JavaScript 做到这一点?
date.setMinutes(date.getMinutes() + ...)
变体的答案都将无法跨越夏令时边界。例如(假设“2014-03-09”是夏令时边界):var d = new Date('2014-03-09 01:59:00'), f = new Date(d.getTime()); d.setMinutes(d.getMinutes() + 30);
d
现在比 f
早 30 分钟,而不是晚。
f
和 d
,您会看到一个显示“GMT-0500”,另一个显示“GMT-0400”(或任何您的时区)。此外,如果您同时在 f
和 d
上调用 .getTime()
,您会看到 f
大于 d
(即稍后)。
01:89
将变为 02:29
,在您“向前跃进”的那一天不存在。 Chrome 决定应该是 01:29
,FF 决定 03:29
。在您“回退”的那晚,两个浏览器都会跳过“回退”时间并向前跳 90 分钟,到达 02:29
。以下是一些 JSFiddle 演示:"spring forward" / "fall back"
使用库
如果您正在做大量的日期工作,您可能需要查看 JavaScript 日期库,例如 Datejs 或 Moment.js。例如,对于 Moment.js,这很简单:
var newDateObj = moment(oldDateObj).add(30, 'm').toDate();
香草 Javascript
这类似于 chaos's answer,但在一行中:
var newDateObj = new Date(oldDateObj.getTime() + diff*60000);
其中 diff
是您希望与 oldDateObj
的时间相差的分钟数。它甚至可以是负面的。
或者作为可重用功能,如果您需要在多个地方执行此操作:
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
如果这不是很明显,我们将分钟乘以 60000
的原因是将分钟转换为毫秒。
小心 Vanilla 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;
}
var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 30 );
alert ( d2 );
Date
对象。 var d = new Date(); d.setMinutes(d.getMinutes() + 30);
var oldDateObj = new Date(); var newDateObj = new Date(); newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000));控制台.log(newDateObj);
setTime
返回数字毫秒时间戳,而不是日期对象。 (不要以为你可以做一个单行。)
var in30Mins = new Date(+new Date() + 1.8e6)
是单衬,但不确定它是否比双衬更好。 ;-)
+new Date()
:stackoverflow.com/a/221565 但是,使用该链接中的信息,我相信以下是可以的:new Date(Date.now() + (30 * 60 * 1000))
var now = new Date(); now.setMinutes(now.getMinutes() + 30); // 现在时间戳 = new Date(now); // 日期对象 console.log(now);
setMinutes
返回时间戳,但 now
仍然是 Date
对象,因此 now = new Date(now)
已过时
也许是这样的?
var d = 新日期(); var v = 新日期(); v.setMinutes(d.getMinutes()+30);控制台.log(v)
Date
对象。 var d = new Date(); d.setMinutes(d.getMinutes() + 30);
If a parameter you specify is outside of the expected range, setMinutes() attempts to update the date information in the Date object accordingly.
我总是创建 7 个函数来处理 JS 中的日期:
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;
};
date.addHours(3, 30)
增加 3 小时 30 分钟。 addYears 需要几年、几个月和几天,addMonths 需要几个月和几天,addMinutes 需要分钟、秒、毫秒等。
new Date().addHours(4).addMinutes(45);
你可以调用尽可能多的,因为这些方法返回“this”,它是当前的日期对象。
var dt = new Date();
然后 dt.addMinutes(45); dt.addHours(4);
甚至 dt.addMinutes(285);
或 dt.addMinutes(45).addHours(4);
都可以工作。如果您对某些代码示例有疑问,请在此处发布您的问题,我很乐意为您提供帮助。
一行代码
var afterSomeMinutes = new Date(new Date().getTime() + minutes * 60000);
其中 minutes
是一个数字
停止使用 Moment.js
正如其他出色答案所建议的那样,在大多数情况下,最好在处理日期时使用库。但是,重要的是要知道,截至 2020 年 9 月,Moment.js 被视为旧版,不应再用于新项目。
在他们的 official docs 中引用 Moment 的声明:
我们希望阻止 Moment 被用于未来的新项目。 [...] 我们现在通常认为 Moment 是一个处于维护模式的遗留项目。它没有死,但它确实完成了。
现代图书馆
以下是 Moment 推荐的替代方案。
卢克森
Luxon 可以被认为是 Moment 的演变。它由 Moment 的长期贡献者 Isaac Cambron 撰写。请阅读 Luxon 文档中的 Why does Luxon exist? 和 For Moment users 页。
语言环境:国际提供
时区:国际提供
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 主页上。
语言环境:可以单独导入的自定义数据文件
时区:国际提供,通过单独的配套库
import {addMinutes} from 'date-fns'
function addMinutesDemo(date, minutes) {
return addMinutes(date, minutes)
}
js-乔达
js-Joda 是 Java Three-Ten Backport 的 JavaScript 端口,它是 Java SE 8 java.time
包的 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()
}
最简单的解决方法是认识到在 javascript 中日期只是数字。它开始 0
或 'Wed Dec 31 1969 18:00:00 GMT-0600 (CST)
。每 1
代表一毫秒。您可以通过获取值并使用该值实例化新日期来增加或减少毫秒。有了这种想法,您就可以很容易地管理它。
const minutesToAdjust = 10;
const millisecondsPerMinute = 60000;
const originalDate = new Date('11/20/2017 10:00 AM');
const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));
console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)
单线无公用事业:
new Date(+new Date() + 60000*15) // +15 minutes
这就是我所做的,似乎效果很好:
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));
return new Date(this.getTime() + minutes * 60000);
,我不需要临时 copiedDate。 ;-)
您应该获取当前日期的值以获取带有 (ms) 的日期并将 (30 * 60 *1000) 添加到它。现在你有(当前日期 + 30 分钟)与 ms
console.log('with ms', Date.now() + (30 * 60 * 1000)) console.log('new Date', new Date(Date.now() + (30 * 60 * 1000)))
它很简单;
let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));
这是 ES6 版本:
let getTimeAfter30Mins = () => {
let timeAfter30Mins = new Date();
timeAfter30Mins = new Date(timeAfter30Mins.setMinutes(timeAfter30Mins.getMinutes() + 30));
};
像这样称呼它:
getTimeAfter30Mins();
我觉得这里的许多答案都缺乏创造性的成分,而这对于时间旅行计算来说是非常需要的。我提出了 30 分钟时间翻译的解决方案。
(jsfiddle here)
function fluxCapacitor(n) {
var delta,sigma=0,beta="ge";
(function(K,z){
(function(a,b,c){
beta=beta+"tT";
switch(b.shift()) {
case'3':return z('0',a,c,b.shift(),1);
case'0':return z('3',a,c,b.pop());
case'5':return z('2',a,c,b[0],1);
case'1':return z('4',a,c,b.shift());
case'2':return z('5',a,c,b.pop());
case'4':return z('1',a,c,b.pop(),1);
}
})(K.pop(),K.pop().split(''),K.pop());
})(n.toString().split(':'),function(b,a,c,b1,gamma){
delta=[c,b+b1,a];sigma+=gamma?3600000:0;
beta=beta+"im";
});
beta=beta+"e";
return new Date (sigma+(new Date( delta.join(':')))[beta]());
}
这是我的单行:
console.log('time:', new Date(new Date().valueOf() + 60000))
你可以这样做:
让 30 分钟 = 30 * 60 * 1000; // 将 30 分钟转换为毫秒 let date1 = new Date();让 date2 = 新日期(date1.getTime() + 三十分钟);控制台.log(date1);控制台.log(date2);
我知道这个话题太老了。但我很确定仍有一些开发人员需要这个,所以我为你制作了这个简单的脚本。我希望你喜欢它!
您好,现在是 2020 年,我添加了一些修改,希望现在对您有所帮助!
再次您好,现在是 2022 年,我再次回来解决一些问题并为方法和函数提供更好的命名。
函数 addTimeToDate(addTime, date){ let generatedTime = date.getTime(); if(addedTime.seconds) generatedTime += 1000 * addedTime.seconds; //检查额外的秒数 if(addedTime.minutes) generatedTime += 1000* 60 * addedTime.minutes;//检查额外的分钟数 if(addedTime.hours) generatedTime += 1000 * 60 * 60 * addedTime.hours;//检查额外小时返回新日期(生成时间); } Date.prototype.addTime = function(addedTime){ return addTimeToDate(addedTime, this); } let futureDate = new Date().addTime({ hours: 16, //加一小时分:45,//加四十五分秒:0 //加0秒返回不加任何秒,所以我们可以删除它. });
${!isAfternoon?this.getHours():this.getHours()-halfDay}:${this.getMinutes()}${isAfternoon?'PM':'AM'}
; }
new Date().strtotime({hours: 8, minutes: 25}).toAmericanFormat();
使用已知的现有库来处理处理时间计算所涉及的怪癖。我目前最喜欢的是moment.js。
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script>
var now = moment(); // get "now"
console.log(now.toDate()); // show original date
var thirty = moment(now).add(30,"minutes"); // clone "now" object and add 30 minutes, taking into account weirdness like crossing DST boundries or leap-days, -minutes, -seconds.
console.log(thirty.toDate()); // show new date
</script>
var add_minutes = function (dt, minutes) {
return new Date(dt.getTime() + minutes*60000);
}
console.log(add_minutes(new Date(2014,10,2), 30).toString());
“添加” 30 分钟的一种方法是创建第二个日期对象(主要用于演示)和 set the minutes 到 minutes + 30
。如果第一次距离下一个小时不到 30 分钟,这也将考虑调整小时。 (即 4:45
到 5:15
)
const first = new Date(); console.log("第一次约会:", first.toString()); const second = new Date(first); const newMinutes = second.getMinutes() + 30; console.log("新分钟数:", newMinutes); second.setMinutes(newMinutes); console.log("第二个日期:", second.toString());
对于像我这样的懒人:
Kip 在咖啡脚本中的回答(从上面),使用“枚举”,并在同一个对象上操作:
Date.UNIT =
YEAR: 0
QUARTER: 1
MONTH: 2
WEEK: 3
DAY: 4
HOUR: 5
MINUTE: 6
SECOND: 7
Date::add = (unit, quantity) ->
switch unit
when Date.UNIT.YEAR then @setFullYear(@getFullYear() + quantity)
when Date.UNIT.QUARTER then @setMonth(@getMonth() + (3 * quantity))
when Date.UNIT.MONTH then @setMonth(@getMonth() + quantity)
when Date.UNIT.WEEK then @setDate(@getDate() + (7 * quantity))
when Date.UNIT.DAY then @setDate(@getDate() + quantity)
when Date.UNIT.HOUR then @setTime(@getTime() + (3600000 * quantity))
when Date.UNIT.MINUTE then @setTime(@getTime() + (60000 * quantity))
when Date.UNIT.SECOND then @setTime(@getTime() + (1000 * quantity))
else throw new Error "Unrecognized unit provided"
@ # for chaining
这是 IsoString 版本:
console.log(new Date(new Date().setMinutes(new Date().getMinutes() - (30))).toISOString());
其他解决方案:
var dateAv = new Date();
var endTime = new Date(dateAv.getFullYear(), dateAv.getMonth(), dateAv.getDate(), dateAv.getHours(), dateAv.getMinutes() + 30);
只是另一种选择,我写道:
如果这是您需要的所有日期处理,那就太矫枉过正了,但它会做您想做的事。
支持日期/时间格式、日期数学(添加/减去日期部分)、日期比较、日期解析等。它是自由开源的。
您只需将此代码与 momnet
库一起使用:
console.log(moment(moment()).add(30,"minutes").format('MM/DD/YYYY hh:mm:ss'));
var myDate= new Date();
var MyNewDate = new Date
(myDate.getFullYear(),myDate.getMonth(),myDate.getDate(),myDate.getMinutes()+10,01,01)
不定期副业成功案例分享