1

I am working in javascript and am trying to format a date that I am receiving in this format 2017-07-31 to this format July 31, 2017.

Is there a best practice on accomplishing this?

programmerGuy
  • 29
  • 3
  • 11

2 Answers2

5

An option with modern browsers (yes, including IE11 surprisingly) is to use Date#toLocaleString

var dateString = "2017-07-31"; // you have a date string in this format
var date = new Date(dateString+'T00:00:00'); // force LOCAL time, 
// without the T00:00:00 the Date would be UTC
// and Western hemisphere dates will be a day out
options = {
    year: 'numeric', month: 'long', day: 'numeric'
};
console.log(date.toLocaleString('en-US', options));
// en-US, the only format that does Month Day, Year

If you are going to be doing a lot of dates, a more performant method is to use Intl.DateTimeFormat

var dateString = "2017-07-31";
var date = new Date(dateString+'T00:00:00');
options = {
  year: 'numeric', month: 'long', day: 'numeric'
};

var fmt = new Intl.DateTimeFormat('en-US', options);
// now use fmt.format(dateobject) as many times as you wish
console.log(fmt.format(date));
Jaromanda X
  • 47,382
  • 4
  • 58
  • 76
  • Fair enough, but this question has been asked a million times before. Maybe two million… The marked duplicates have 78 answers between them. – RobG Aug 01 '17 at 04:24
  • yes, but the ACCEPTED answer in the (only) duplicate others pointed out was 7 years old or something :p – Jaromanda X Aug 01 '17 at 04:27
  • I wouldn't use a Date at all, reformatting the string and replacing the month is two lines of code and completely avoids Date vagaries. ;-) – RobG Aug 01 '17 at 04:31
-1

You should use momentjs, it's very easy to format.

var dateStr = '2017-07-31';
var date = moment(dateStr, 'YYYY-MM-DD');
moment(date.format('MMMM Do, YYYY');