rashmi
rashmi

Reputation:

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 but it didn't work. Please suggest how to do this.

Upvotes: 8

Views: 20457

Answers (4)

Heretic Monkey
Heretic Monkey

Reputation: 12113

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 = new Date(Date.UTC(2000, 0, 3, 0, 0, 0));
const mondayName = new Intl.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.

Upvotes: 1

Vertigo
Vertigo

Reputation: 2746

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

Upvotes: 5

Espo
Espo

Reputation: 41919

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 = new Date;
alert(today.getDayName());

Upvotes: 2

Kieron
Kieron

Reputation: 11814

var date = new Date();
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];

Upvotes: 21

Related Questions