tags:

views:

1800

answers:

4

given a date object,how to get previous week's first day

+4  A: 

This Datejs library looks like it can do that sort of thing relatively easily.

thomasrutter
wow this library is awesome!
hayato
+2  A: 

Code:

function getPreviousSunday()
{
    var today=new Date();
    return new Date().setDate(today.getDate()-today.getDay()-7);
}


function getPreviousMonday()
{
    var today=new Date();
    if(today.getDay() != 0)
      return new Date().setDate(today.getDate()-7-6);
    else
      return new Date().setDate(today.getDate()-today.getDay()-6);
}

Reasoning:

Depends what you mean by previous week's first day. I'll assume you mean previous sunday for the sake of this discussion.

To find the number of days to subtract:

  • Get the current day of the week.
  • If the current day of the week is Sunday you subtract 7 days
  • If the current day is Monday you subtract 8 days

...

  • If the current day is Saturday 13 days

The actual code once you determine the number of days to subtract is easy:

var previous_first_day_of_week=new Date().setDate(today.getDate()-X);

Where X is the above discussed value. This value is today.getDay() + 7

If by first day of the week you meant something else, you should be able to deduce the answer from the above steps.

Note: It is valid to pass negative values to the setDate function and it will work correctly.

For the code about Monday. You have that special case because getDay() orders Sunday before Monday. So we are basically replacing getDay() in that case with a value of getDay()'s saturday value + 1 to re-order sunday to the end of the week.

We use the value of 6 for subtraction with Monday because getDay() is returning 1 higher for each day than we want.

Brian R. Bondy
+1  A: 

First day of week can be either Sunday or Monday depending on what country you are in:

function getPrevSunday(a) {
    return new Date(a.getTime() - ( (7+a.getDay())*24*60*60*1000 ));
};

function getPrevMonday(a) {
    return new Date(a.getTime() - ( (6+(a.getDay()||7))*24*60*60*1000 ));
};

If you want to set a dateobject to the previous sunday you can use:

a.setDate(a.getDate()-7-a.getDay());

and for the previous monday:

a.setDate(a.getDate()-6-(a.getDay()||7));
some
+2  A: 
function previousWeekSunday(d) { 
    return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 7); 
}

function previousWeekMonday(d) { 
    if(!d.getDay())
        return new Date(d.getFullYear(), d.getMonth(), d.getDate() - 13); 
    return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 6); 
}
Prestaul
You have a bug in the previousWeekMonday. Every sunday only goes 6 days back.
some
Great catch. Fixed.
Prestaul