8

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.

1
  • Remember, javascript is case sensitive Commented Jan 30, 2009 at 14:36

4 Answers 4

21
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];
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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());

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.