开发者

Javascript time manupulation

How to get 20 days before date fr开发者_StackOverflow中文版om a date in javascript?

for example:

today =March 3, 2010

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


This is a way to do it:

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

you can also construct and use a 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);

The same goes for hours, minutes, months etc.

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


// 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);


This article suggests extending the Date class with an explicit capability to add and subtract days:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜