3

I have a date like this

2017-06-23 and my desired output is

Friday June 23 2017

 v.npi.appointment_dates[j] = date.toLocaleString('en-US', {year: 'numeric', month: 'long', day: 'numeric' });

But because of the day: 'numeric' I am missing the day name. Can anyone please help me?

Yann Bertrand
  • 3,084
  • 1
  • 22
  • 38
Duster
  • 99
  • 3
  • 9

2 Answers2

5

You need to include weekday: 'long' in the options object:

var date = new Date();
console.log(date.toLocaleString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }));

If you want to adopt the the browser default language, use undefined:

var date = new Date();
console.log(date.toLocaleString(undefined, {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }));

Even with options support, the result of toLocaleString is still implementation dependent as the "locale" option is actually a language code, which may not be what the user expects even if they speak that language and the browser developers may not have chosen the expected format.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

Here is the function you're looking for.

function getFormattedDate(date) {
  var dayNames = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
  var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

  var dayOfMonth = date.getDate()
  var dayOfWeekIndex = date.getDay()
  var monthIndex = date.getMonth()
  var year = date.getFullYear()

  return dayNames[dayOfWeekIndex] + ' ' + monthNames[monthIndex] + ' ' +  dayOfMonth + ' ' + year;
}

You should take a look at moment.js which will help you a lot with formatting and tons of other date issues.

Yann Bertrand
  • 3,084
  • 1
  • 22
  • 38