admin管理员组

文章数量:1312907

For a datepicker I need two dates: from: today - 7 days, to: today + 7 days.

I get a currentDate with:

  var toDay = new Date();
  var curr_date = toDay.getDate();
  var curr_month = toDay.getMonth();
  curr_month++;
  var curr_year = toDay.getFullYear();
  var toDay = (curr_month + "/" + curr_date + "/" + curr_year);

How to get 7 days+ and 7 days- dates ? With corresponding month!

For a datepicker I need two dates: from: today - 7 days, to: today + 7 days.

I get a currentDate with:

  var toDay = new Date();
  var curr_date = toDay.getDate();
  var curr_month = toDay.getMonth();
  curr_month++;
  var curr_year = toDay.getFullYear();
  var toDay = (curr_month + "/" + curr_date + "/" + curr_year);

How to get 7 days+ and 7 days- dates ? With corresponding month!

Share Improve this question edited Oct 31, 2013 at 13:50 Coderbit asked Oct 31, 2013 at 13:34 CoderbitCoderbit 8013 gold badges10 silver badges32 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

As per ment, You can use following code

var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);
var nextWeekDate = ((myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear());

myDate = new Date();
myDate.setDate(myDate.getDate() -7 );
var prevWeekDate = ((myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear());

Modified Demo

Javascript saves a date as the number of milliseconds since midnight on january 1st 1970. You can get this time by calling "getTime()" on the Date object. You can then add 7X24X60X60X1000 to get 7 days later, or substract them for 7 days earlier represented in milliseconds. Then call Date.setTime() again.

edit: both these other methods involving getDate() get unpredictable when you are around the start or end of a month.

Pretty simple:

nextWeek.setDate(toDay.getDate() + 7);
lastWeek.setDate(toDay.getDate() - 7);

You can also extend your javascript Date object like this

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

Date.prototype.substractDays = function(days) {
    this.setDate(this.getDate() - days);
    return this;
};

     //then
var dateDiff=7;
var toDay = new Date();
var futureDay= new Date(toDay.addDays(dateDiff));
var prevDay = new Date(toDay.substractDays(dateDiff*2)); // substracted 14 daysbecause 'toDay' value has been incresed by 7 days

Hope this helps.

You can add /subtract like following

var fdate= new Date();
var numberofdayes= 7;
fdate.setDate(fdate.getDate() + numberofdayes); 

(Not sure whether you are asking that or not)

Then you can format it in dd/mm/yyyy using getDate(), getMonth() and getFullYear(). (Don't forget to add 1 to fdate.getMonth())

var formateddate = fdate.getDate()+ '/'+ fdate.getMonth()+1 + '/'+ fdate.getFullYear();

本文标签: dateJavascript daysfrom todayStack Overflow