-2

Does Javascript not have any built in support for formatting dates? I have a date object, and I want to format it to a format of my choice e.g. the date that I want to convert is '2017-12-22'. Is there not any function that I could use

something like var newFormattedDate = new Date('2017-12-22', 'mm/dd/yyyy')

so that the output is 22/12/2017

Rafey Hijazy
  • 81
  • 1
  • 5
  • First, No. JS does not have one. You can look into `localeDateString` or `DateString` functions but they have compatibility issues and are not consistent with format. Second, HOW in the world are you expecting format as `22/12/2017` when you pass format as `mm/dd/yyyy`? – Rajesh Dec 22 '17 at 05:55
  • Yes, it doesn't have support for formatting. – RobG Dec 23 '17 at 04:18
  • @Rajesh Here's a link to how I expect to pass format as dd/mm/yy as opposed to mm/dd/yy: https://gist.github.com/mlconnor/1887156 . Thanks for the info though – Rafey Hijazy May 15 '18 at 06:53
  • @RafeyHijazy You should look into `moment.js` – Rajesh May 15 '18 at 09:37
  • Alright. Thanks Rajesh. – Rafey Hijazy May 16 '18 at 11:50

1 Answers1

1

Javascript doesn't have support to give format to date. You can use moment.js.

Alternatively, you can use string#replace.

console.log('2017-12-22'.replace(/(....)-(..)-(..)/g,'$3/$2/$1'));
Aarif Aslam
  • 967
  • 9
  • 15