Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Giving format do date with javascrip

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading