Javascript时间操纵

时间:2011-03-08 09:28:05

标签: javascript

如何从javascript中的日期开始前20天获取?

例如:

today =March 3, 2010

seven_days_b4 = subtract 7 days from today //What i want is:  February 25, 2010

3 个答案:

答案 0 :(得分:2)

这是一种方法:

var today = new Date
  , todayminus7days = new Date(today).setDate(today.getDate()-7);
console.log(new Date(today)); //=>current date
console.log(new Date(todayminus7days)); //=>current date minus 7 days

你也可以构建和使用prototoype.method:

Date.prototype.subtractDays = function(days){
  return new Date(this).setDate(this.getDate()-days);
}
//usage
var dateMinus20Days = new Date().subtractDays(20);
var dateSpecifiedMinus20Days = new Date('2005/10/13').subtractDays(20);

同样适用于小时,分钟,月等。

Date.prototype.subtractHours = function(hours){
  return new Date(this).setHours(this.getHours()-hours);
}
Date.prototype.subtractMonths = function(months){
  return new Date(this).setMonth(this.getMonth()-months);
}
Date.prototype.subtractMinutes = function(minutes){
  return new Date(this).setMinutes(this.getMinutes()-minutes);
}

答案 1 :(得分:1)

// Tue Mar 08 2011 01:32:41 GMT-0800 (PST)
var today = new Date();

var millisecondsIn20Days = 20 * 24 * 60 * 60 * 1000;
// Wed Feb 16 2011 01:32:41 GMT-0800 (PST)
var twentyDaysAgo = new Date(today - millisecondsIn20Days);

答案 2 :(得分:0)

article建议使用显式添加和减去天数的功能扩展Date类:

 Date.prototype.addDays = function(days) {
         this.setDate(this.getDate()+days);
 }