Amra Amra - 1 year ago 70
Javascript Question

Javascript function to bring current day of the week info not working

I created this function long time ago which it was displaying the information required to the web page for the current day of the week.

I have not changed the code since then, but it is now displaying the previous day's information (e.g. on Thursday it shows Wednesday's information).

I was hoping that someone could help me figure out what's wrong with the function below:

$(document).ready(function () {
var dayOfWeek = new Date().getDay();

if (dayOfWeek > 0 && dayOfWeek <= 5 )
$("#menu" + dayOfWeek).show();

Any help would be much appreciated.

The function is supposed to bring information from Monday to Friday.
On JSFiddle it works fine ( but on the home page of the webpage it does not seem to bring the correct date.
It migh be an issue with the feed?
However there is another page on the website which uses a similar function and it works ok.
On this page is not bringing "Jueves"/Thursday

On this page is showing "Jueves"/ Thurday.

Which indicate that the data should be ok.

Any ideas?


Answer Source

JavaScript's Date#getDay() method returns the index of the current day (0-6), where Sunday is day 0 and Saturday is day 6.

console.log(['Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat'][new Date().getDay()]);

Pay careful attention to this note from the spec (emphasis mine):

Return value
An integer number corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.

The date it returns will match the current date from your browser. You can try logging new Date() to verify what it thinks the date is.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download