0

Possible Duplicate:
Get first and last day of the week in JavaScript

Can any body advice how i can get start date and end date of last week by giving todays date to the function?

Community
  • 1
  • 1
Jeet Singh
  • 402
  • 1
  • 5
  • 12

3 Answers3

9

Below is the working code! hope this can help anybody ...!

    var d = new Date();
        var to = d.setTime(d.getTime() - (d.getDay() ? d.getDay() : 7) * 24 * 60 * 60 * 1000);
        var from = d.setTime(d.getTime() - 6 * 24 * 60 * 60 * 1000);
alert(to);
alert(from);
Jeet Singh
  • 402
  • 1
  • 5
  • 12
0

you can use Date.js

 Date.today().previous().monday()

May be it works for you.

Ajay Kadyan
  • 1,081
  • 2
  • 13
  • 36
0

Get the last day of the month:

/**
 * Accepts either zero, one, or two parameters.
 *     If zero parameters: defaults to today's date
 *     If one parameter: Date object
 *     If two parameters: year, (zero-based) month
 */
function getLastDay() {
    var year, month;
    var lastDay = new Date();

    if (arguments.length == 1) {
        lastDay = arguments[0];
    } else if (arguments.length > 0) {
        lastDay.setYear(arguments[0]);
        lastDay.setMonth(arguments[1]);
    }

    lastDay.setMonth(lastDay.getMonth() + 1);
    lastDay.setDate(0);

    return lastDay;
}

Get the last Monday:

/**
 * Accepts same parameters as getLastDay()
 */
function getLastMonday() {
    var lastMonday = getLastDay.apply(this, arguments);
    lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay() == 0 ? 6 : (lastMonday.getDay() - 1)));
    return lastMonday;
}

Now to do your work you can do

/**
 * Accepts one parameter: Date object.
 * Assumes start of week is Sunday.
 */
function getWeek(d) {
    var jan1 = new Date(d.getFullYear(), 0, 1);
    return Math.ceil((((d - jan1) / (24 * 60 * 60 * 1000)) + jan1.getDay() + 1) / 7);
}

and then use

// Get the last week of this month:
var lastWeekThisMonth = getWeek(getLastDay());
Alert("lastWeekThisMonth: %s", lastWeekThisMonth);
Jigar Pandya
  • 6,004
  • 2
  • 27
  • 45