Skipper Skipper - 21 days ago 10
Javascript Question

Finding where to start counting in a Calendar application

enter image description here

Hello, I'm new here and couldn't quite find an answer to this specific Javascript question--Basically, I have a Calendar application made in HTML that's made up of 7 rows and 6 columns, with Sunday on the far left and Saturday on the far right. I'm using Javascript to fill each cell with the appropriate day number.

This Calendar application needs to be able to find out which day of the week to start counting from. So for example, if someone used the application next month, this application would need to automatically know to start day 1 on a Thursday; if they used it two months from now, the application would need to start day 1 on a Sunday, etc, etc...

So if you think of Sunday as day 0 and Saturday as day 6, I would need a way to count the number of days after Sunday that the first day of the month starts on. For example, if the first day of the month is a Wednesday, it would need to start day one three days after Sunday. If the first day of the month is a Sunday, it would need to start day one zero days after Sunday.

What type of algorithm would I need to use to make this work properly?

Answer

You are basically asking for the offset (of empty days) before the month starts in a calendar view.

It's easiest to work with a Date object, the most important methods are (only those that are probably relevant to you):

  • Constructor: new Date(<year>, <month>, <day>), the month is 0-based

  • Year: getFullYear(), setFullYear(<year>)

  • Month: getMonth(), setMonth(<month>), the month is 0-based

  • Day: getDate(), setDate(<day>)

  • Weekday: getDay(), from 0=Sunday to 6=Saturday

So in your case it is very easy:

  1. Create a date with the first of the month (e.g. Nov 2016: var d = new Date(2016, 10, 1);).
  2. Call d.getDay() to get the offset.

If you would have Monday as first day (which is imho more logical, even the bible says you should rest on the 7th day and not the 1st ;-) then the formula would be (d.getDay() + 6) % 7 or alternatively create the date from the 6th of the month. Weekends aren't split up that way and the word weekend implies also that the Saturday and Sunday are at the end of the week.

This is a practical answer, but you could do the math yourself, although I really don't recommend it. You just have to know the weekday for one date and the rules for leap years. All calculations can be done from there. However as the saying goes: don't reinvent the wheel.