Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 693
PlanBuildr Avatar asked Oct 29 '25 10:10

PlanBuildr


1 Answers

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
like image 180
Sabu Monkey Avatar answered Oct 31 '25 00:10

Sabu Monkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!