Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何向JavaScript日期对象添加30分钟?_Javascript_Date_Date Manipulation - Fatal编程技术网

如何向JavaScript日期对象添加30分钟?

如何向JavaScript日期对象添加30分钟?,javascript,date,date-manipulation,Javascript,Date,Date Manipulation,我想得到一个比另一个日期对象晚30分钟的日期对象。如何使用JavaScript实现它? var oldDateObj=new Date(); var newDateObj=新日期(); setTime(oldDateObj.getTime()+(30*60*1000)); console.log(newDateObj)可能是这样的 var d=新日期(); var v=新日期(); v、 设置分钟数(d.getMinutes()+30); console.log(v)使用库 如果您正在做大量的

我想得到一个比另一个日期对象晚30分钟的日期对象。如何使用JavaScript实现它?

var oldDateObj=new Date();
var newDateObj=新日期();
setTime(oldDateObj.getTime()+(30*60*1000));

console.log(newDateObj)可能是这样的

var d=新日期();
var v=新日期();
v、 设置分钟数(d.getMinutes()+30);
console.log(v)
使用库 如果您正在做大量的日期工作,您可能希望查看JavaScript日期库,如或。例如,对于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小时来得到明天的约会,对吧?错了

事实证明,如果用户遵守夏令时,一天不一定是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!
这就是为什么如果您必须大量使用上述库,那么使用其中一个库是更安全的选择

下面是我编写的这个函数的一个更通用的版本。我仍然建议您使用库,但这对您的项目来说可能有些过分/不可能。语法是根据函数建模的

/**
 * 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 now=newdate();
now.setMinutes(now.getMinutes()+30);//时间戳
现在=新日期(现在);//日期对象

console.log(现在)这就是我所做的工作,似乎效果很好:

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中的日期:
addSeconds
addMinutes
addHours
addDays
addWeeks
addMonths
addYears

您可以在此处看到一个示例:

如何使用:

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 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;
};

对于像我这样懒惰的人:

Kip在coffeescript中的答案(从上面),使用“枚举”,并在同一对象上操作:

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

使用已知的现有库来处理处理时间计算所涉及的怪癖。我现在最喜欢的是


var now=moment();//现在就开始
console.log(now.toDate());//显示原始日期
var三十=时刻(现在)。加上(30,“分钟”);//克隆“now”对象并添加30分钟,同时考虑到跨越DST边界或闰日,-分,-秒等奇怪情况。
console.log(three.toDate());//显示新日期

以下是ES6的版本:

let getTimeAfter30Mins = () => {
  let timeAfter30Mins = new Date();
  timeAfter30Mins = new Date(timeAfter30Mins.setMinutes(timeAfter30Mins.getMinutes() + 30));
};
可以这样说:

getTimeAfter30Mins();

我觉得这里的许多答案都缺乏创造性的成分,这是时间旅行计算所急需的。我给出了30分钟的时间翻译解决方案

(jsfiddle)


最简单的解决方法是认识到在javascript中日期只是数字。它开始于1969年12月31日星期三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)
您可以这样做:

让三十分钟=30*60*1000;//将30分钟转换为毫秒
设date1=新日期();
让date2=新日期(date1.getTime()+三十分钟);
console.log(date1);
控制台日志(日期2)这是我的一行:


console.log('time:',new Date(new Date().valueOf()+60000))
我知道这个主题太老了。但是我很确定有些开发人员仍然需要这个,所以我为您制作了这个简单的脚本。 我希望你喜欢

大家好,现在是2020年,我已经添加了一些修改,希望它现在能帮上大忙

函数strottime(日期、添加时间){
让generatedTime=date.getTime();
如果(addTime.seconds)generatedTime+=1000*addTime.seconds;//检查是否有额外的秒数
如果(addTime.minutes)generatedTime+=1000*60*addTime.minutes;//检查是否有额外的分钟数
如果(addTime.hours)generatedTime+=1000*60*60*addTime.hours;//检查是否有额外的小时数
返回新日期(生成时间);
}
Date.prototype.strotime=函数(addTime){
返回strotime(new Date(),addTime);
}
让futureDate=新日期().strtotime({
小时数:16,//增加一小时
分钟:45,//加上45分钟
秒:0//添加0秒返回到不添加任何秒,以便我们可以删除它。
});

走向未来
您应该获取当前日期的值,以获取带有(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))
以下是IsoString版本:

console.log(新日期(new Date().setMinutes)(新日期().getMinutes()-(30))).toISOString())其他解决方案:

var dateAv = new Date();
var endTime = new Date(dateAv.getFullYear(), dateAv.getMonth(), dateAv.getDate(), dateAv.getHours(), dateAv.getMinutes() + 30);
          
这是简单的,因为它是

let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));
停止使用Moment.js 正如其他优秀答案所建议的,在大多数情况下,处理日期时最好使用库。然而,重要的是要知道,截至2020年9月,JS被考虑。
var dateAv = new Date();
var endTime = new Date(dateAv.getFullYear(), dateAv.getMonth(), dateAv.getDate(), dateAv.getHours(), dateAv.getMinutes() + 30);
          
let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));
var myDate= new Date();
var MyNewDate = new Date 
(myDate.getFullYear(),myDate.getMonth(),myDate.getDate(),myDate.getMinutes()+10,01,01)
var add_minutes =  function (dt, minutes) {
return new Date(dt.getTime() + minutes*60000);
}
 console.log(add_minutes(new Date(2014,10,2), 30).toString());