tags:

views:

41

answers:

4

Hi All, I am using a dropdownlist and a calendar control in my page. In that I am having following list items. 1)Last Week 2)last month

If I choose last week in the dropdownlist the calendar control should display the date range from date 7 days ago and today's date. How can I get it through Java Script

+3  A: 
// current date
var now = new Date();
// 7 days earlier
now.setDate(now.getDate()-7);
RaYell
A: 
var curDate = new Date();
var prevDate = new Date();

prevDate.setDate ( curDate.getDate() - 7 );
rahul
Hi It shows the difference of date only. For example Today's date is 1. This function gives the output as -6.but the need is 26/01/2010 to 01/02/2010
susanthosh
if (sValue == "lastweek") {var cdate = new Date();var dateString = cdate.getMonth() + "/" + cdate.getDate() + "/" + cdate.getFullYear() + " "var pdate = cdate.setDate(cdate.getDate() - 7);alert(pdate);radTRStart.set_SelectedDate = pdate.format("mm/dd/yyyy");Use this script function any dropdown selected change event. You will come to know the difficulty.
susanthosh
A: 
// no need to declare beginingOfLastWeek if you won't need it any more - tempDate will be enough just fix the code
var now = new Date(),
    beginingOfLastWeek = new Date(),
    tempDate = new Date();

    beginingOfLastWeek.setDate(now.getDate() - 7 - now.getDay());
    tempDate.setTime(beginingOfLastWeek.getTime());

// format it, print it, do anything you want with it
for(var i = 0; i < 7; i++) {
    tempDate.setDate(beginingOfLastWeek.getDate() + i);
    console.log(tempDate);
}
// and print today for whatever reason you need it
console.log(now);

this would display last weeks 7 days (monday till sunday) + today

if you need 7 days from 7 days ago till today just remove from this line

beginingOfLastWeek.setDate(now.getDate() - 7 - now.getDay() - 1);

the "now.getDay() - 1" bit and increase the iterator from 7 to 8.

cheers Tom

Tom Tu
oh and we need to initialize 3 copies of new Date() as objects are assigned through reference and we need independent instances to be able to alter the date without affecting other variables - so now stays now and so on.
Tom Tu
A: 

How about using DateJS library?

Its return

  • 7 days ago => Monday, January 25, 2010 12:00:00 AM
  • last week => Monday, January 25, 2010 12:00:00 AM
  • last month => Friday, January 01, 2010 12:00:00 AM
S.Mark
I want this only. Can you tell me how to use this?
susanthosh
There is documentation page here http://code.google.com/p/datejs/wiki/APIDocumentation
S.Mark