简体   繁体   中英

How to format a JavaScript date object using Intl.DateTimeFormat

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM