【问题标题】:Format Date to long format [duplicate]将日期格式化为长格式[重复]
【发布时间】:2018-01-07 17:10:56
【问题描述】:

我正在使用 javascript 并尝试将我收到的日期格式为2017-07-31 格式为July 31, 2017 格式。

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

【问题讨论】:

  • @AlexanderNied - 是的,但公认的答案是老派:p
  • 您可以重新格式化日期字符串,而无需转换为 Date 对象(这更容易且更不容易出错)。

标签: javascript date


【解决方案1】:

现代浏览器的一个选项(是的,令人惊讶的是包括 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));

【讨论】:

  • 很公平,但这个问题已经被问过一百万次了。也许两百万……标记的重复项之间有 78 个答案。
  • 是的,但是其他人指出的(仅)重复项中的 ACCEPTED 答案是 7 岁之类的:p
  • 我根本不会使用日期,重新格式化字符串并替换月份是两行代码,完全避免了日期的变幻莫测。 ;-)
【解决方案2】:

你应该使用momentjs,它很容易格式化。

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

【讨论】:

  • 您的答案不应依赖于 OP 中未标记或提及的库。
猜你喜欢
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-27
相关资源
最近更新 更多