Day Name from Date in JS

JavascriptJquery

Javascript Problem Overview


I need to display the name of the day given a date (like "05/23/2014") which I get from a 3rd party.

I've tried using Date, but I only get the date.

What is the correct way to get the name of the day?

Javascript Solutions


Solution 1 - Javascript

Ahum, three years later...

Why nobody uses the methods provided by the standard javascript Date class (except Callum Linington)?

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Getting the day name from a date:

function getDayName(dateStr, locale)
{
	var date = new Date(dateStr);
	return date.toLocaleDateString(locale, { weekday: 'long' });		
}

var dateStr = '05/23/2014';
var day = getDayName(dateStr, "nl-NL"); // Gives back 'Vrijdag' which is Dutch for Friday.

Getting all weekdays in an array:

function getWeekDays(locale)
{
	var baseDate = new Date(Date.UTC(2017, 0, 2)); // just a Monday
	var weekDays = [];
	for(i = 0; i < 7; i++)
	{		
		weekDays.push(baseDate.toLocaleDateString(locale, { weekday: 'long' }));
		baseDate.setDate(baseDate.getDate() + 1);		
	}
	return weekDays;
}

var weekDays = getWeekDays('nl-NL'); // Gives back { 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag', 'zondag'} which are the days of the week in Dutch.

For American dates use 'en-US' as locale.

Solution 2 - Javascript

You could use the Date.getDay() method, which returns 0 for sunday, up to 6 for saturday. So, you could simply create an array with the name for the day names:

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(dateString);
var dayName = days[d.getDay()];

Here dateString is the string you received from the third party API.

Alternatively, if you want the first 3 letters of the day name, you could use the Date object's built-in toString method:

var d = new Date(dateString);
var dayName = d.toString().split(' ')[0];

That will take the first word in the d.toString() output, which will be the 3-letter day name.

Solution 3 - Javascript

use the Date.toLocaleString() method :

new Date(dateString).toLocaleString('en-us', {weekday:'long'})

Solution 4 - Javascript

let weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][new Date().getDay()]

Solution 5 - Javascript

To get the day from any given date, just pass the date into a new Date object:

let date = new Date("01/05/2020");
let day = date.toLocaleString('en-us', {weekday: 'long'});
console.log(day);
// expected result = tuesday

To read more, go to mdn-date.prototype.toLocaleString()(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)

Solution 6 - Javascript

var days = [
    "Sunday",
    "Monday",
    "...", //etc
    "Saturday"
];

console.log(days[new Date().getDay()]);

Simple, read the Date object in JavaScript manual

To do other things with date, like get a readable string from it, I use:

var d = new Date();
d.toLocaleString();

If you just want time or date use:

d.toLocaleTimeString();
d.toLocaleDateString();

You can parse dates either by doing:

var d = new Date(dateToParse);

or

var d = Date.parse(dateToParse);

Solution 7 - Javascript

let weekday = new Date(dateString).toLocaleString('en-us', {weekday:'long'});
console.log('Weekday',weekday);

Solution 8 - Javascript

Take a look at this :

var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('ar-EG', options));
// expected output: الخميس، ٢٠ ديسمبر، ٢٠١٢

console.log(event.toLocaleDateString('ko-KR', options));
// expected output: 2012년 12월 20일 목요일

Source : Mozilla Doc

Solution 9 - Javascript

One line solution :

const day = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"][new Date().getDay()]

Solution 10 - Javascript

Easiest and simplest way:

var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayName = days[new Date().getDay()];

Solution 11 - Javascript

Try using this code:

var event = new Date();
var options = { weekday: 'long' };
console.log(event.toLocaleDateString('en-US', options));

this will give you the day name in string format.

Solution 12 - Javascript

I'm not a fan of over-complicated solutions if anyone else comes up with something better, please let us know :)

any-name.js

var today = new Date().toLocaleDateString(undefined, {
	day: '2-digit',
	month: '2-digit',
	year: 'numeric',
	weekday: 'long'
});
any-name.html
<script>
	document.write(today);
</script>

Solution 13 - Javascript

Solution No.1

var today = new Date();

  var day = today.getDay();

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

  var dayname = days[day];

  document.write(dayname);

Solution No.2

	  var today = new Date();

  var day = today.getDay();

  switch(day){
    case 0:
    day = "Sunday";
    break;

    case 1:
    day = "Monday";
    break;

    case 2:
    day ="Tuesday";
    break;

    case 3:
    day = "Wednesday";
    break;

    case 4:
    day = "Thrusday";
    break;

    case 5:
    day = "Friday";
    break;

    case 6:
    day = "Saturday";
    break;
  }


document.write(day);

Solution 14 - Javascript

Shortest one liner

Change the UTC day from 6 to 5 if you want Array to start from Sunday.

const getWeekDays = (locale) => [...Array(7).keys()].map((v)=>new Date(Date.UTC(1970, 0, 6+v)).toLocaleDateString(locale, { weekday: 'long' }));

console.log(getWeekDays('de-DE')); 

Solution 15 - Javascript

One more option is to use the inbuilt function Intl.DateTimeFormat, e.g.:

const getDayName = (dateString) =>
  new Intl.DateTimeFormat('en-Us', { weekday: 'long' }).format(new Date(dateString));

<label for="inp">Enter a date string in the format "MM/DD/YYYY" or "YYYY-MM-DD" and press "OK":</label><br>
<input type="text" id="inp" value="01/31/2021">
<button onclick="alert(getDayName(document.getElementById('inp').value))">OK</button>

Solution 16 - Javascript

var dayName =['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var day = dayName[new Date().getDay()];
console.log(day)

Solution 17 - Javascript

you can use an object

var days = {
   'Mon': 'Monday',
   'etc..': 'etc..',
   'Fri': 'Friday'
}

var date = new Date().toString().split(' ')[0]; //get day abreviation first
console.log(days[date]);

Solution 18 - Javascript

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// request a weekday along with a long date
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(date.toLocaleDateString('de-DE', options));
// → "Donnerstag, 20. Dezember 2012"

// an application may want to use UTC and make that visible
options.timeZone = 'UTC';
options.timeZoneName = 'short';
console.log(date.toLocaleDateString('en-US', options));
// → "Thursday, December 20, 2012, UTC"

Solution 19 - Javascript

Just use it:

function getWeekDayNames(format = 'short', locale = 'ru') {
  const names = [];
  const date = new Date('2020-05-24');
  let days = 7;

  while (days !== 0) {
    date.setDate(date.getDate() + 1);
    names.push(date.toLocaleDateString(locale, { weekday: format }));
    days--;
  }

  return names;
}

About formats you can read here Documentation DateTimeFormat

Solution 20 - Javascript

Not the best method, use an array instead. This is just an alternative method.

http://www.w3schools.com/jsref/jsref_getday.asp

var date = new Date();
var day = date.getDay();

You should really use google before you post here.

Since other people posted the array method I'll show you an alternative way using a switch statement.

switch(day) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;

    ... rest of cases

    default:
        // do something
        break;
}

The above works, however, the array is the better alternative. You may also use if() statements however a switch statement would be much cleaner then several if's.

Solution 21 - Javascript

I solved this problem in this way. Hope that may help you
let dateString = '5/23/2014'  

// converting Date String to Javascript Date Format
let day = new Date(dateString).getDay();
let month = new Date(dateString).getMonth()
let year =  new Date(dateString).getFullYear()
let dayName;

if (day ==0){
    dayName= 'Sunday'
}else if (day == 1){
    dayName= 'Monday'
}else if (day == 2){
    dayName= 'Tuesday'
}else if (day == 3){
    dayName= 'Wednesday'
}else if (day == 4){
    dayName= 'Thursday'
}else if (day ==5){
    dayName= 'Friday'
}else {
    dayName= 'Saturday'
}

console.log(`Day : ${dayName} Month: ${month+1} Year : ${year}`)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDhrubaJyotiView Question on Stackoverflow
Solution 1 - JavascriptRWCView Answer on Stackoverflow
Solution 2 - JavascriptJoeytje50View Answer on Stackoverflow
Solution 3 - JavascriptiamnoxView Answer on Stackoverflow
Solution 4 - JavascriptAlexandre VieiraView Answer on Stackoverflow
Solution 5 - JavascriptNavneetKaur0111View Answer on Stackoverflow
Solution 6 - JavascriptCallum LiningtonView Answer on Stackoverflow
Solution 7 - JavascriptDr NVSView Answer on Stackoverflow
Solution 8 - JavascriptBorisDView Answer on Stackoverflow
Solution 9 - JavascriptMarc DuboisView Answer on Stackoverflow
Solution 10 - JavascriptFortuneCookieView Answer on Stackoverflow
Solution 11 - Javascripthardik patelView Answer on Stackoverflow
Solution 12 - JavascriptEdgar KelevraView Answer on Stackoverflow
Solution 13 - JavascriptAravind ChaudharyView Answer on Stackoverflow
Solution 14 - JavascriptchickensView Answer on Stackoverflow
Solution 15 - JavascriptRoman KaragodinView Answer on Stackoverflow
Solution 16 - JavascriptDivyanshi MishraView Answer on Stackoverflow
Solution 17 - JavascriptLuis CView Answer on Stackoverflow
Solution 18 - JavascriptMaddyView Answer on Stackoverflow
Solution 19 - JavascriptAlexander ZakusiloView Answer on Stackoverflow
Solution 20 - JavascriptNicolasView Answer on Stackoverflow
Solution 21 - JavascriptRumanView Answer on Stackoverflow