Bharat
Bharat

Reputation: 41

How to calculate date range for week and month in javascript?

Can someone guide me on date range in JavaScript?

I want to calculate one week and month date range from today's date; I.e, if today is "18th july 2010", the range for the week should be "11/07/2010 - 8/07/2010" and for the month it should be "01/07/2010 - 18/07/2010".

Thanks for your guidance in advance.

Upvotes: 4

Views: 9961

Answers (3)

vitmalina
vitmalina

Reputation: 1889

Here is vanilla JS function that will take a date (or blank) as input and return an object with start and end date of that week (assuming Monday is first day of week :) )

function rangeWeek (dateStr) {
    if (!dateStr) dateStr = new Date().getTime();
    var dt = new Date(dateStr);
    dt = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
    dt = new Date(dt.getTime() - (dt.getDay() > 0 ? (dt.getDay() - 1) * 1000 * 60 * 60 * 24 : 6 * 1000 * 60 * 60 * 24));
    return { start: dt, end: new Date(dt.getTime() + 1000 * 60 * 60 * 24 * 7 - 1) };
}

console.log(rangeWeek());
console.log(rangeWeek('2013/9/1'));

You can change accordingly for Sunday-Saturday.

Upvotes: 1

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

Try this:

var now = new Date();
var nextWeek = new Date(new Date(now).setDate(now.getDate() + 7));
var nextMonth = new Date(new Date(now).setMonth(now.getMonth() + 1));

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

I would recommend you looking at the excellent datejs library which has many useful functions to manipulate dates.

Upvotes: 1

Related Questions