Printing parts of a date with words in JavaScript

You already know how to print the day of the week as a number using the getDay method. Often, however, we do not need the number of the day of the week, but its textual name. Let's write code that will convert the numbers returned by the getDay method into the corresponding names of the days of the week.

First, let's write a code that will display the number of the current day of the week:

let date = new Date(); let day = date.getDay(); console.log(day);

And now let's refine this code so that the screen displays not the number of the day of the week, but its name (for brevity, Sunday will be 'Sun', Monday 'Mon' and so on)

To solve the problem, we will make an array of days of the week days and start it from Sunday (since this is the zero day):

let days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

How to use this array to display, for example, 'Tue'? You need to pass the number of this day in square brackets (Tuesday has the number 2):

let days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; console.log(days[2]); // shows 'Tue'

However, we don't want to pass the day of the week manually, but rather let JavaScript detect the current day and display its name. To do this, we need to combine what the getDay method returns with our days array:

let date = new Date(); let day = date.getDay(); let days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; console.log(days[day]);

Let the following array be given:

let months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];

Use this array to output the name of the current month.

enru