How to get start date of a week in JavaScript

This is little tricky to get the start date or/and end date of a week. Also, there is no standard day that should be a REAL start day in a week. In my example, I assume that the start day is Monday. Also, I will show you how you can adjust it to fit your needs. So, you can make it as Saturday or Sunday or whatever.

In my example, suppose I want to make a title like “Accepting Bookings For the Week of START_DATE to END_DATE”. So, within this week, it should be same. But in next week, it should be changed automatically.

Well, it’s not hard, let’s look at the code:
[html]

You may also read:  Create a dynamic image gallery using ajax, jquery and php (XML also)

Accepting Bookings For the Week of Feb 23rd to Feb 23rd

//
[/html]

There is some vita points. First month array, I needed to use that to print the month name as JavaScript has no function to print month name. So, when we will get the month number (0, 1, 2 etc) we will print the same index of month array. Note that getMonth() function returns the month number based on zero, so January would be 0, February would be 1 and so on.

Next one is:
[javascript]
startDate = d.getDate() – day + (day == 0 ? -6:1)
[/javascript]

This is where you need to edit if you change the start day. Change -6 to something between -1 to -7 and you will see the result.

You may also read:  Create multi level drop down menu in css

And then the following line set the end date:
[javascript]
endDate = startDate + 6;
[/javascript]

If you want to make it for next week, then change this line
[javascript]
startDate = d.getDate() – day + (day == 0 ? -6:1)
[/javascript]

to

[javascript]
startDate = (d.getDate() + 7) – day + (day == 0 ? -6:1)
[/javascript]

And finally, I set the correct value in correct place:
[javascript]
document.getElementById(‘ds’).innerHTML = month[correctStartDate.getMonth()] + ” ” + correctStartDate.getDate();
document.getElementById(‘dl’).innerHTML = month[correctEndDate.getMonth()] + ” ” + correctEndDate.getDate();
[/javascript]

:)

You may also like...

Leave a Reply

%d bloggers like this: