Mor*_*eng 721 javascript date date-manipulation
我想得到一个比另一个Date对象晚30分钟的Date对象.我如何使用JavaScript?
Kip*_*Kip 892
如果你正在做很多日期工作,你可能想要查看像Datejs或Moment.js这样的JavaScript日期库.例如,使用Moment.js,这很简单:
var newDateObj = moment(oldDateObj).add(30, 'm').toDate();
Run Code Online (Sandbox Code Playgroud)
这就像混乱的答案,但是在一行中:
var newDateObj = new Date(oldDateObj.getTime() + diff*60000);
Run Code Online (Sandbox Code Playgroud)
diff
您想要oldDateObj
的时间差异在哪里?它甚至可能是消极的.
或者作为可重用的函数,如果您需要在多个位置执行此操作:
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
Run Code Online (Sandbox Code Playgroud)
您可能认为可以在24小时内添加日期以获取明天的日期,对吗?错误!
addMinutes(myDate, 60*24); //DO NOT DO THIS
Run Code Online (Sandbox Code Playgroud)
事实证明,如果用户观察夏令时,则一天不一定是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!
Run Code Online (Sandbox Code Playgroud)
这就是为什么使用上述库之一是一个更安全的赌注,如果你必须做很多工作.
下面是我写的这个函数的更通用的版本.我仍然建议使用一个库,但这可能对您的项目来说是过度/不可能的.语法是在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;
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*mie 215
var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 30 );
alert ( d2 );
Run Code Online (Sandbox Code Playgroud)
cha*_*aos 146
var oldDateObj = new Date();
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000));
console.log(newDateObj);
Run Code Online (Sandbox Code Playgroud)
小智 99
var now = new Date();
now.setMinutes(now.getMinutes() + 30); // timestamp
now = new Date(now); // Date object
console.log(now);
Run Code Online (Sandbox Code Playgroud)
aln*_*sre 48
var afterSomeMinutes = new Date(new Date().getTime() + minutes * 60000);
Run Code Online (Sandbox Code Playgroud)
哪里minutes
有一个数字
Tyl*_*ter 43
也许是这样的?
var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+30);
console.log(v)
Run Code Online (Sandbox Code Playgroud)
Jac*_*obi 31
我总是创建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));
Run Code Online (Sandbox Code Playgroud)
这是功能:
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;
};
Run Code Online (Sandbox Code Playgroud)
Joh*_*ams 24
单行无公用事业:
new Date(+new Date() + 60000*15) // +15 minutes
Run Code Online (Sandbox Code Playgroud)
tsa*_*des 12
最简单的解决方法是识别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)
Run Code Online (Sandbox Code Playgroud)
Dun*_*Luk 11
正如其他很棒的答案所推荐的那样,在大多数情况下,最好在处理日期时使用库。但是,重要的是要知道,自 2020 年 9 月起,Moment.js 被视为旧版,不应再用于新项目中。
在他们的官方文档中引用 Moment 的声明:
我们不鼓励在未来的新项目中使用 Moment。[...] 我们现在通常认为 Moment 是处于维护模式的遗留项目。它没有死,但它确实已经完成了。
以下是 Moment 推荐的替代方案。
Luxon 可以被认为是 Moment 的进化。它的作者是Isaac Cambron,他是Moment 的长期贡献者。请阅读为什么 Luxon 存在?以及Luxon 文档中的For Moment 用户页面。
Intl
提供Intl
提供import {DateTime} from 'luxon'
function addMinutes(date, minutes) {
return DateTime.fromJSDate(date).plus({minutes}).toJSDate()
}
Run Code Online (Sandbox Code Playgroud)
Day.js 旨在成为 Moment.js 的极简替代品,使用类似的 API。它不是替代品,但如果您习惯使用 Moment 的 API 并希望快速行动,请考虑使用 Day.js。
Intl
通过插件提供import dayjs from 'dayjs'
function addMinutes(date, minutes) {
return dayjs(date).add(minutes, 'minutes').toDate()
}
Run Code Online (Sandbox Code Playgroud)
Date-fns 提供了一系列用于操作 JavaScriptDate
对象的函数。有关更多详细信息,请滚动到“为什么使用 date-fns?” 在 date-fns 主页上。
Intl
通过单独的配套库提供import {addMinutes} from 'date-fns'
function addMinutesDemo(date, minutes) {
return addMinutes(date, minutes)
}
Run Code Online (Sandbox Code Playgroud)
js-Joda 是 Java 的三十后向端口的 JavaScript 端口,它是 Java SE 8java.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()
}
Run Code Online (Sandbox Code Playgroud)
这就是我所做的,它看起来效果很好:
Date.prototype.addMinutes = function(minutes) {
var copiedDate = new Date(this.getTime());
return new Date(copiedDate.getTime() + minutes * 60000);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样调用它:
var now = new Date();
console.log(now.addMinutes(50));
Run Code Online (Sandbox Code Playgroud)
您应该获取当前日期的值以获取带有 (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)))
Run Code Online (Sandbox Code Playgroud)
小智 7
它很简单;
let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));
Run Code Online (Sandbox Code Playgroud)
let d = new Date();
d.setMinutes(d.getMinutes() + 30);
// console.log(d)
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
let thirtyMinutes = 30 * 60 * 1000; // convert 30 minutes to milliseconds
let date1 = new Date();
let date2 = new Date(date1.getTime() + thirtyMinutes);
console.log(date1);
console.log(date2);
Run Code Online (Sandbox Code Playgroud)
这是ES6版本:
let getTimeAfter30Mins = () => {
let timeAfter30Mins = new Date();
timeAfter30Mins = new Date(timeAfter30Mins.setMinutes(timeAfter30Mins.getMinutes() + 30));
};
Run Code Online (Sandbox Code Playgroud)
称之为:
getTimeAfter30Mins();
Run Code Online (Sandbox Code Playgroud)
我觉得这里的许多答案缺乏创意组件,非常需要时间旅行计算.我提出了30分钟的时间翻译解决方案.
(这里是 jsfiddle )
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]());
}
Run Code Online (Sandbox Code Playgroud)
这是我的单线:
console.log('time: ', new Date(new Date().valueOf() + 60000))
Run Code Online (Sandbox Code Playgroud)
我知道这个话题太老了。但我很确定有一些开发人员仍然需要这个,所以我为您制作了这个简单的脚本。我希望你喜欢它!
大家好,现在是 2020 年了,我添加了一些修改,希望现在能更好地帮助您!
大家好,现在是 2022 年,我再次回来修复一些问题并为方法和函数提供更好的命名。
function addTimeToDate(addedTime, date){
let generatedTime = date.getTime();
if(addedTime.seconds) generatedTime += 1000 * addedTime.seconds; //check for additional seconds
if(addedTime.minutes) generatedTime += 1000* 60 * addedTime.minutes;//check for additional minutes
if(addedTime.hours) generatedTime += 1000 * 60 * 60 * addedTime.hours;//check for additional hours
return new Date(generatedTime);
}
Date.prototype.addTime = function(addedTime){
return addTimeToDate(addedTime, this);
}
let futureDate = new Date().addTime({
hours: 16, //Adding one hour
minutes: 45, //Adding fourty five minutes
seconds: 0 //Adding 0 seconds return to not adding any second so we can remove it.
});
Run Code Online (Sandbox Code Playgroud)
<button onclick="console.log(futureDate)">Travel to the future</button>
Run Code Online (Sandbox Code Playgroud)
这是 IsoString 版本:
console.log(new Date(new Date().setMinutes(new Date().getMinutes() - (30))).toISOString());
Run Code Online (Sandbox Code Playgroud)
小智 5
var add_minutes = function (dt, minutes) {
return new Date(dt.getTime() + minutes*60000);
}
console.log(add_minutes(new Date(2014,10,2), 30).toString());
Run Code Online (Sandbox Code Playgroud)
“添加”30 分钟的一种方法是创建第二个日期对象(主要用于演示)并将分钟设置为minutes + 30
。如果第一次时间距下一小时不到 30 分钟,这也将考虑调整小时。(即,4:45
到5:15
)
const first = new Date();
console.log("first date :", first.toString());
const second = new Date(first);
const newMinutes = second.getMinutes() + 30;
console.log("new minutes:", newMinutes);
second.setMinutes(newMinutes);
console.log("second date:", second.toString());
Run Code Online (Sandbox Code Playgroud)