get last week in javascript

后端 未结 3 803
逝去的感伤
逝去的感伤 2021-01-07 07:41

I am using the following in a script:

var startDate = new Date(\"10/12/2012\");
var endDate = new Date(\"10/18/2012\");

I would like those

相关标签:
3条回答
  • 2021-01-07 08:01

    Using date.js to get last Sunday

    Date.today().moveToDayOfWeek(0, -1); // -1 indicates to go back
    

    Best to use a library to manipulate dates. It will make your life a lot easier.

    Having said that have a long-term aim to understand dates in JavaScript. It will help you with things like debugging.

    0 讨论(0)
  • 2021-01-07 08:04

    The Javascript datetime object does not have a format method. You'll need to use a library or generate the string yourself:

    var curr = new Date; // get current date
    var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
    var last = first + 6; // last day is the first day + 6
    var startDate = new Date(curr.setDate(first));
    startDate = "" + (startDate.getMonth() + 1) + "/" + startDate.getDate() + "/" + startDate.getFullYear();
    var endDate = new Date(curr.setDate(last));
    endDate = "" + (endDate.getMonth() + 1) + "/" + endDate.getDate() + "/" + endDate.getFullYear();
    

    Here's a fiddle http://jsfiddle.net/DPQeB/2/ and its output

    11/18/2012
    11/24/2012

    One library that allows you to format dates is jQuery UI.

    0 讨论(0)
  • 2021-01-07 08:12

    If starting from sunday:

    var today = new Date();
    var sundayOfWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - today.getDay()-8);
    var mondayOfWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - today.getDay()+1);
    
    console.log( mondayOfWeek );
    console.log( sundayOfWeek );
    
    0 讨论(0)
提交回复
热议问题