Skip to content Skip to sidebar Skip to footer

Javascript Full Names For Day-of-week And Month (or How To Get The Date Names Per Client Locale)

The string that is returned from (new Date()).toString() looks something like this: 'Tue Nov 22 2016 14:14:51 GMT-0800 (Pacific Standard Time)' Is there a built-in method/construc

Solution 1:

If you don't need to support old browsers (older than IE 11), you can use toLocalDateString().

Example:

newDate().toLocaleDateString('en-US', {
    weekday: 'long',
    month: 'long',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    timeZoneName: 'short'
})

But moment.js is way more comfortable.

See MDN Date.prototype.toLocaleDateString() for more information.

Solution 2:

As Josa's answer implies, it is possible to get the full names for the weekday and month (for most modern browsers).

I used the .toLocaleDateString() to extract the full names of the weekday and month in the language of the client successfully using Chrome and IE11 (it does NOT work in Safari 9).

Extending the idea of getting the full names from the browser, I was curious if we could, then, get the name of the weekday and the name of the month in the language that matches the client's locale. The following experiment shows that that it is possible (although, not reliable).

For Experiment/Fun:

The following function will return an object that includes the name of the Weekday and Month for a particular date in the language of a particular locale-code.

Fiddle

functiongetWeekdayAndMonthNamesByLocaleCode(localeCode, date) {
  varNames = {
    Weekday: "",
    Month: ""
  };

  if (!(date instanceofDate && !isNaN(date.valueOf()))) {
    date = newDate();
  }

  if (localeCode == null || localeCode.length < 2) {
    localeCode = navigator.language;
  }

  Names.Month = date.toLocaleDateString(localeCode, {
    month: 'long',
  });

  Names.Weekday = date.toLocaleDateString(localeCode, {
    weekday: 'long'
  });

  returnNames;
}

I haven't tested the function for browser compatibility and I certainly wouldn't rely on it to work for all languages, but I thought it was interesting enough to post here for others to experiment with.

Post a Comment for "Javascript Full Names For Day-of-week And Month (or How To Get The Date Names Per Client Locale)"