170

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?

Casey Falk
  • 2,617
  • 1
  • 18
  • 29
DhrubaJyoti
  • 1,845
  • 2
  • 13
  • 10
  • convert it to a date, then call `getDay()` to get the day number (0-6, 0==Sunday), and then use an array of the day names to map the number to the name. – forgivenson Jul 28 '14 at 15:31
  • // The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" function getDayName(dateString) { let dayName = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][new Date(dateString).getDay()]; return dayName; } let result = getDayName(10/12/2022); console.log(result); – Asif Ur Rahman Dec 02 '22 at 20:54

23 Answers23

305

Use the methods provided by the standard JavaScript Date class:

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.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
RWC
  • 4,697
  • 2
  • 22
  • 29
  • 4
    I was not aware of this method existing at all at the time of posting my solution. Very nice solution indeed. It's also nice that this directly provides internationalisation. Also, it's nice to learn something new :P – Joeytje50 Aug 02 '17 at 19:48
  • 1
    A possible reason some people may not use it is because, according to the page you linked to, it seems there is not full compatibility with locales on mobile platforms. – John Jun 01 '18 at 16:37
  • @John Jun: True. Currently, most browsers on mobile devices support it. Most notable, the default Android browser does not. Chrome on Android does. (It is advised to use Chrome on Android anyway.. Different discussion.) – RWC Jun 06 '18 at 14:52
  • Only partially works in IE10. weekday is recognized but always returns the long name, even if I specify 'short'. 'short' does work in Chrome. Also IE10 doesn't recognize the 'month' keyword. It just returns a date, like 'Thu Jan 1 1970' when used with 'long', whereas Chrome does return the long month names. – Larphoid Dec 15 '18 at 16:27
  • Hmm, let me rephrase that. After some more fiddling, IE10 doesn't seem to bother with anything you specify, not even the locale. It always returns a full date with long names according to the OS locale. – Larphoid Dec 17 '18 at 15:08
  • I had to explicitly specify UTC timezone, or it would use my local timezone and give me the previous day: return date.toLocaleDateString("en-US", { weekday: 'short', timeZone: 'UTC' }); – tronman Dec 19 '18 at 17:22
  • Hum… The date string you pass as an argument to the function is not normalized (ISO8601). Is the Dutch date format you are using here retrieved as a locale? – Brice Coustillas Aug 06 '19 at 04:44
  • @Brice: Passing a date string in ISO8601 format (in the example '2014-05-23') works. See https://www.iso.org/iso-8601-date-and-time-format.html – RWC Sep 02 '19 at 14:12
  • @RWC: It does — but "var dateStr = '05/23/2014';" yields no ISO8601 date. Now I understand that passing the locale as a second parameter will allow for date-format transformation to canonic ISO8601. Am I right? – Brice Coustillas Sep 14 '19 at 10:31
  • There is no "Date class", there is a built–in Date constructor. The options for *toLocaleString* are part of ECMA-402, they aren't part of ECMAScript (i.e. "standard javascript"). [Support for toLocaleString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Browser_compatibility) is patchy, particularly for languages other than English. – RobG Sep 27 '19 at 12:12
  • Thanks for the answer, but this did not work for some locales like `uz-Latn-UZ` in Chrome. Does anyone know how one could contribute to Chrome so that it is supported? Thanks – ddsultan Nov 04 '20 at 21:51
178

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.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95
  • 23
    This is probably NOT the best way to do it. The standard Javascript Date class provides ways to get the full name. Have a look at my answer. – RWC Aug 02 '17 at 15:29
  • But..."standard Javascript date class" doesn't work in all browsers. – Hernán Eche Nov 07 '19 at 14:50
  • @HernánEche according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date every single browser supports Date just fine. Which browser does it not work for you? – Joeytje50 Nov 10 '19 at 15:36
  • @Joeytje50 WebView from JavaFx, but ok, doesn't qualify as 'browser' – Hernán Eche Nov 11 '19 at 16:10
  • 1
    @HernánEche JavaFx, as far as I can find on the internet, is Java, not JavaScript. These languages are completely different, so you should try looking for things related to Java. See https://www.thesoftwareguild.com/faq/difference-between-java-and-javascript/ (or any other result on Google under "difference between java and javascript") for more information about that. – Joeytje50 Nov 11 '19 at 16:42
  • 1
    @Joeytje50 If you keep searching, you will "find on the internet" that Javascript can be run from Java too, with WebView objects and WebEngine you can load web pages, creates document models, css styles and runs JavaScript, you are welcome. – Hernán Eche Nov 11 '19 at 17:02
  • @HernánEche Okay, I was not aware of that. Regardless, I have never heard about that and I have no idea what kind of features are supported by it. If you have a solution for Java's WebView / WebEngine, feel free to post it either as a seperate answer below, or if you are not able to find it anywhere else, feel free to post a new question here on SO. For my answer, however, I can't really help you, I'm sorry. – Joeytje50 Nov 14 '19 at 10:16
  • Only about 1/3 of the world uses Sunday as the first day of the week, so this is just plain wrong for 2/3 of the world, including Europe: https://commons.wikimedia.org/wiki/File:First_Day_of_Week_World_Map.svg – Software Engineer Jul 27 '21 at 14:34
  • @SoftwareEngineer Then I've got good news for you: Just call sunday the 7th day, take modulo 7, and you've got yourself exactly this list! Anyway, front-end users will never even see this array. The array is just a computer-readable list that converts this number into a string. I'm not sure what's wrong about my answer; if anything, `Date.getDay()` returning `0` for sunday would be the thing that is "wrong" for 2/3rds of the world then, right? I've just implemented something that deals with this fact. I never claimed sunday was the first day of the week... or the last day, for that matter. – Joeytje50 Jul 31 '21 at 13:04
53

use the Date.toLocaleString() method :

new Date(dateString).toLocaleString('en-us', {weekday:'long'})
iamnox
  • 539
  • 4
  • 4
31
let weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][new Date().getDay()]
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
13
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);
Callum Linington
  • 14,213
  • 12
  • 75
  • 154
10

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)

NavneetKaur0111
  • 117
  • 1
  • 8
9
let weekday = new Date(dateString).toLocaleString('en-us', {weekday:'long'});
console.log('Weekday',weekday);
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Dr NVS
  • 191
  • 3
  • 5
7

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

BorisD
  • 1,611
  • 17
  • 22
5

One line solution :

let day = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"][new Date().getDay()]
whoami
  • 147
  • 2
  • 4
4

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>
Roman Karagodin
  • 740
  • 2
  • 11
  • 16
3

Easiest and simplest way:

var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayName = days[new Date().getDay()];
FortuneCookie
  • 1,756
  • 3
  • 25
  • 41
3

var dayName =['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var day = dayName[new Date().getDay()];
console.log(day)
Divyanshi Mishra
  • 110
  • 1
  • 11
2

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.

HarshitMadhav
  • 4,769
  • 6
  • 36
  • 45
  • 3
    A [solution with *toLocaleString*](https://stackoverflow.com/a/45464959/257182) was posted 2 years earlier, why is this answer needed? – RobG Sep 27 '19 at 12:09
2

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>
2

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')); 
chickens
  • 19,976
  • 6
  • 58
  • 55
2

This method doesn't require you to set a random date or know the stringLocale beforehand. This method is independent from predefined values. The locale can be retrieved from the client.

Automatically fill the weekdays array in the string locale.

const locale = 'en-US' // Change this based on client settings
const date = new Date()

const weekdays = []
while(!weekdays[date.getDay()]) {
  weekdays[date.getDay()] = date.toLocaleString(locale, { weekday: 'long'})
  date.setDate(date.getDate() + 1)
}

console.log(weekdays)

If you want the locale names for the months as well;

const locale = 'en-US' // Change this based on client settings
const date = new Date()
date.setMonth(0) // Not strictly needed, but why not..
date.setDate(1) // Needed because if current date is >= 29, the month Feb can get skipped.

const months = []
while(!months[date.getMonth()]) {
  months[date.getMonth()] = date.toLocaleString(locale, { month: 'long'})
  date.setMonth(date.getMonth() + 1)
}

console.log(months)

I currently use it like this: (As you can see, I make a clone of the current date and set the month and date to their first occurance)

const date = new Date()

let locale = navigator.languages
    ? navigator.languages[0]
    : (navigator.language || navigator.userLanguage)
let clone = new Date(date.getFullYear(), 0, 1, 0, 0, 0, 0)

let weekdays = []
while (!weekdays[clone.getDay()]) {
  weekdays[clone.getDay()] = {
    index: clone.getDay(),
    long: clone.toLocaleString(locale, { weekday: 'long' }),
    short: clone.toLocaleString(locale, { weekday: 'short' })
  }
  clone.setDate(clone.getDate() + 1)
}
clone.setDate(clone.getDate() - weekdays.length) // Reset

let months = []
while (!months[clone.getMonth()]) {
    months[clone.getMonth()] = {
        index: clone.getMonth(),
        long: clone.toLocaleString(locale, { month: 'long' }),
        short: clone.toLocaleString(locale, { month: 'short' })
    }
    clone.setMonth(clone.getMonth() + 1)
}
clone.setMonth(clone.getMonth() - months.length) // Reset

let hours = []
while (!hours[clone.getHours()]) {
    hours[clone.getHours()] = {
        index: clone.getHours(),
        hour24: clone.toLocaleTimeString(locale, { hour12: false, hour: '2-digit', minute: '2-digit' }),
        hour12: clone.toLocaleTimeString(locale, { hour12: true, hour: 'numeric' })
    }
    clone.setHours(clone.getHours() + 1)
}
clone.setHours(clone.getHours() - hours.length) // Reset

console.log(locale)
console.log(weekdays)
console.log(months)
console.log(hours)
console.log(clone.toLocaleString())
Hugo Cox
  • 389
  • 4
  • 15
1

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);
tgallei
  • 827
  • 3
  • 13
  • 22
0

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]);
Luis C
  • 49
  • 7
0

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

Alexander Zakusilo
  • 1,466
  • 3
  • 16
  • 34
0
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"
Maddy
  • 503
  • 6
  • 17
0

// Solve this problem with a function. // The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"

function getDayName(dateString) {
   let dayName = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][new Date(dateString).getDay()];
        return dayName;
    }
    let result = getDayName(10/12/2022);
    console.log(result);
Asif Ur Rahman
  • 101
  • 1
  • 2
0

Use toLocaleString method with options. Also here is way to get list of weekday names dynamically for given locale.

const dayName = (date, locale = "en-US") =>
  date.toLocaleString(locale, { weekday: "long" });

const getWeekdayNames = (startDayIndex = 0, locale = "en-US") => {
  if (!(startDayIndex >= 0 && startDayIndex <= 6)) {
    startDayIndex = 0;
  }
  let time = Date.now();
  const oneDay = 24 * 60 * 60 * 1000;
  while (new Date(time).getDay() !== startDayIndex) time += oneDay;
  return Array(7)
    .fill(0)
    .map((_, i) => dayName(new Date(time + oneDay * i), locale));
};

// Full week day for given date string
console.log(dayName(new Date("2023/07/31")));

// Get list of week day full names starting Sunday in US (default)
console.log(getWeekdayNames());

// Get list of week day full names starting 3rd day in es-BR
console.log(getWeekdayNames(2, "es-BR"));
Siva K V
  • 10,561
  • 2
  • 16
  • 29
-3

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.

Nicolas
  • 1,125
  • 1
  • 15
  • 31