I’m using toLocaleDatestring to give format to my date. Te current function I’m using is the following:
var oDate = new Date().toLocaleDateString('en-US', { year: "numeric", day: "2-digit", month: "short"})
And it actualy works, it’s giving me "Jun 09, 2023" as result
My question is, is there any way to give to it a different format. I’m I want it like "Jun/09/2023"
>Solution :
You could use RegExp:
const date = new Date()
.toLocaleDateString('en-US', { year: "numeric", day: "2-digit", month: "short"})
.replace(/[\s,]+/g, '/');
console.log(date);
Or get separate parts and join them:
const date = new Date()
const formatted = new Intl.DateTimeFormat('en-US', { year: "numeric", day: "2-digit", month: "short"})
.formatToParts(date)
.reduce((str, item) => item.type === 'literal' ? str : str += (str ? '/' : '') + item.value, '')
console.log(formatted)
If you don’t like reduce:
const date = new Date()
const formatted = new Intl.DateTimeFormat('en-US', { year: "numeric", day: "2-digit", month: "short"})
.formatToParts(date)
.filter(item => item.type !== 'literal')
.map(item => item.value)
.join('/')
console.log(formatted)