最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to format a JavaScript date object using Intl.DateTimeFormat - Stack Overflow

programmeradmin2浏览0评论

I am trying to show a date in a string format like it's done in PHP (using 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));

The output is : Friday, 3/13/2020, 2:15:03 PM How do I get something like this : Friday, 13th March 2020 ?

I am trying to show a date in a string format like it's done in PHP (using 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));

The output is : Friday, 3/13/2020, 2:15:03 PM How do I get something like this : Friday, 13th March 2020 ?

Share Improve this question asked Mar 13, 2020 at 14:18 PlanBuildrPlanBuildr 1772 gold badges6 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Here's my version of this, you can use formatToParts() function to get them by part assuming you will be using the same format every time, and then get them by object array so that you can create your own format allowing you to add custom text. Although it would be much more easier and efficient if you will use some other Date formatter.

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

You can try this way:

var isoString = new Date().toISOString();
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var date = new Date(isoString);
var americanDate = new Intl.DateTimeFormat("en-US", options).format(date);
console.log(americanDate); //Friday, March 13, 2020

Using moment.js you can do better date-time format.

发布评论

评论列表(0)

  1. 暂无评论