-2

I need to transform this date that comes from an API in this format

yyyy-mm-ddTHH:mm:ssZ

to

dd-mm-yyyy

do I have to use any library in order to do this?

Dereemii
  • 33
  • 1
  • 6
  • Why that _specific_ format? Why not just respect your users/visitor's system/user default date/time format by simply using `Date.prototype.toLocaleString()`? – Dai Sep 23 '22 at 03:12
  • [Parsing a string to a date in JavaScript](https://stackoverflow.com/q/5619202) – gre_gor Sep 23 '22 at 03:34
  • @Dai—because system preferences for date formats are not dependent on the language setting. Only ECMA-402 makes that assumption. In any case, dates should be presented in an unambiguous format that the author is confident is correct, not some format based on the browser default language. – RobG Sep 23 '22 at 04:28
  • `"2022-07-26T03:00:11.183Z".split(/\D/).slice(0,3).reverse().join('-');`, or `let [y, m, d] = "2022-07-26T03:00:11.183Z".split(/\D/); let date = \`${d}-${m}-${y}\`` or `let date = [d,m,y].join('-')` and so on… – RobG Sep 24 '22 at 07:21

1 Answers1

0

It should be what you need:

let theDate=new Date("2022-07-26T03:00:11.183Z");
let option={
    day:"2-digit",
    month:"2-digit",
    year:"numeric",
}
let result=theDate.toLocaleDateString('en-US',option).replaceAll("/","-")
console.log(result);

If you want the output in dd-mm-yyyy format, you can replace "en-US" with "en-GB".

The KNVB
  • 3,588
  • 3
  • 29
  • 54
  • en-GB uses `dd/MM/yyyy`, not `dd-mm-yyyy`. – Dai Sep 23 '22 at 05:56
  • @Dai—and the difference between MM and mm is…? There is no fixed meaning for formatting tokens, different libraries/environments/languages use different tokens for the same thing and sometimes the same tokens with different meanings. In this case, the language sets the order and options set day and month to two digit. – RobG Sep 24 '22 at 06:58
  • @RobG I’m British. No-one uses dashes to separate date components in the UK, it is **always** a forward-slash. It’s drilled into us since primary school. – Dai Sep 24 '22 at 07:21
  • I didn't say anything about the order or slashes, I was asking about the difference between MM and mm. PS check out the order of date components on the masthead of [*The Times*](https://www.thetimes.co.uk). ;-) – RobG Sep 24 '22 at 11:14