admin管理员组

文章数量:1290945

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.

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.

Share Improve this question edited Oct 9, 2012 at 21:00 the Tin Man 161k44 gold badges221 silver badges306 bronze badges asked Jul 18, 2010 at 9:02 BharatBharat 411 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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));

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

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.

本文标签: How to calculate date range for week and month in javascriptStack Overflow