admin管理员组文章数量:1316518
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
?
2 Answers
Reset to default 4Here'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.
本文标签: How to format a JavaScript date object using IntlDateTimeFormatStack Overflow
版权声明:本文标题:How to format a JavaScript date object using Intl.DateTimeFormat - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742007677a2412288.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论