Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Date to long format [duplicate]

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?

like image 341
programmerGuy Avatar asked Sep 05 '26 10:09

programmerGuy


1 Answers

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));
like image 106
Jaromanda X Avatar answered Sep 07 '26 00:09

Jaromanda X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!