How to display day of week in Javascript.
In my previous tutorial i explained how to get current date and time in javascript. In previous tutorial i discussed about date object. Let’s quickly revise it.
How to Display Day of Week in Javascript
Let’s create a date object.
1 2 3 4 5 6 7 8 9 |
var date = new Date(); /* Print it on console */ console.log(date); /* Output */ Fri Mar 25 2016 17:57:42 GMT+0530 (IST) |
Date provides getDay() method which returns the day number of the week, starting with Sunday on 0 (zero) and so on.
Today is Friday so if i use this method it will return 5.
1 2 3 4 5 6 7 |
var date = new Date(); console.log(date.getDay()); /* Output */ 5 |
How to Print Name of the WeekDay using Javascript
Let’s create a simple method which prints the name of week day.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function printWeekDay () { /* Create a date object */ var date = new Date(); /* Create an array of week name */ var week = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; console.log(week[date.getDay()]); /* Explanation * date.getDay() return day number (suppose it's 5) * week[5] return array value on that index */ } |
How to create an array in javascript.
Print Day of Week using Date in Javascript
Suppose if i enter following date 10/11/2009, print the day of week on the input date.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* Print day of week */ function findDay(myDate) { var date = new Date(myDate); var week = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; console.log(week[date.getDay()]); } findDay(10/11/2009); // Print Sunday findDay(11/10/2010); // Print Wednesday |