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?
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?
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));
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');