Reputation: 177
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
?
Upvotes: 4
Views: 14920
Reputation: 117
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
Upvotes: 4
Reputation: 879
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.
Upvotes: 0