将日期格式化为长格式

pro*_*Guy 3 javascript date

我正在使用 javascript 并试图将我以这种格式收到的日期格式化2017-07-31为这种格式July 31, 2017

是否有实现此目的的最佳实践?

Jar*_*a X 8

现代浏览器的一个选项(是的,包括 IE11 令人惊讶)是使用 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
Run Code Online (Sandbox Code Playgroud)

如果你打算做很多日期,一个更高效的方法是使用 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));
Run Code Online (Sandbox Code Playgroud)