首页 > 解决方案 > 如何使用 Intl.DateTimeFormat 格式化 JavaScript 日期对象

问题描述

我正在尝试以字符串格式显示日期,就像在 PHP 中所做的那样(使用 date())。

let checkoutDate = new Date();

var formatter = new Intl.DateTimeFormat('en-us', {
  weekday: 'long',
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  fractionalSecondDigits: 3,
  hour12: true,
  timeZone: 'UTC'
});

console.log(formatter.format(checkoutDate));

输出是:Friday, 3/13/2020, 2:15:03 PM 我如何得到这样的东西:Friday, 13th March 2020

标签: javascriptdate

解决方案


这是我的版本,您可以使用formatToParts()函数按部分获取它们,假设您每次都将使用相同的格式,然后通过对象数组获取它们,以便您可以创建自己的格式,允许您添加自定义文本. 尽管如果您使用其他日期格式化程序会更容易和更有效。

let checkoutDate = new Date();
var th = 'th';
var formatter = new Intl.DateTimeFormat('en-us', {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  fractionalSecondDigits: 3,
  timeZone: 'UTC'
});
var formatted = formatter.formatToParts(checkoutDate);

var day = formatted[4].value;
var wr = checker(day);

console.log(wr);
console.log(formatted[0].value+ ',', day +wr, formatted[2].value, formatted[6].value);

function checker(x){
    if (x > 3 && x < 21) return 'th';
    switch (x % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    }
}
//output Friday, 13th March 2020

推荐阅读