Skip to content Skip to sidebar Skip to footer

How To Get The Day From A Particular Date Using Javascript

I am new to JavaScript. My requirement is that T want to pop up a message on particular days (like Sunday, Monday...) all through when a date is selected. I tried getday() function

Solution 1:

var date = newDate();
var day = date.getDay();

day now holds a number from zero to six; zero is Sunday, one is Monday, and so on.

So all that remains is to translate that number into the English (or whatever other language) string for the day name:

var name = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][day];

Solution 2:

var days= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var today = newDate();
document.write(days[today.getDay()]);

Solution 3:

This page seems to provide you with what you need.

What we are going to do is to add getMonthName() and getDayName() methods to all our dates so that we can get the month name or day name by calling these new methods directly instead of having to call getMonth() or getDay() and then do an array lookup of the corresponding name.

You can then do:

var today = newDate;
alert(today.getDayName());

Solution 4:

Use the ECMAScript Internationalization API, part of ECMA 402, the second edition of which was introduced alongside ECMAScript 2015, aka 6th Edition, aka ES6.

const knownMonday = newDate(Date.UTC(2000, 0, 3, 0, 0, 0));
const mondayName = newIntl.DateTimeFormat([], {
  weekday: 'long',
  timeZone: 'UTC'
}).format(knownMonday);
console.log(`Name of Monday in current "locale": "${mondayName}"`);

Note while this takes more code, it saves you from having to type out the names of the days in every app you write, in every language you want to support.

Note also I used Date.UTC(year, month, day) to initialize the Date and timeZone: 'UTC' while formatting. This is due to not knowing what time zone the reader may be in; given that, I use UTC both in the declaration and the formatting of the Date to ensure nothing gets changed due to time zone differences.

Post a Comment for "How To Get The Day From A Particular Date Using Javascript"