格式化日期为长格式

时间:2017-08-01 01:26:15

标签: javascript date

我正在使用javascript工作,并且正在尝试将我以此格式2017-07-31收到的日期格式化为此格式July 31, 2017

是否有实现这一目标的最佳做法?

2 个答案:

答案 0 :(得分:2)

使用现代浏览器的选项(是的,包括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




如果你要做很多日期,一个更高效的方法就是使用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));




答案 1 :(得分:-1)

您应该使用momentjs,格式化非常容易。

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