0

Formatting a date takes 1 line of code in PHP but it takes so many lines in JavaScript, at least in old answers.

Is there a new way of going from a variable myDate containing "Mon Apr 20 2020 14:45:34 GMT+0100 (British Summer Time)" to "2020-04-20" in just 1 or 2 lines of code?

Format should be the same across locales so toLocaleDateString() isn't an option.

drake035
  • 3,955
  • 41
  • 119
  • 229
  • Did you also look at this? https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date –  Apr 20 '20 at 14:15
  • Are you referring to toLocaleDateString()? Not an option for me, I don't see any other simple solution on that page – drake035 Apr 20 '20 at 14:17
  • Why should everything be so "simple"? Put your complex code into a function, and reuse the function ... – Teemu Apr 20 '20 at 14:18
  • It's incredibly simple in other languages such as PHP, which immediately raises the question why is it so complicated in JS? – drake035 Apr 20 '20 at 14:23
  • Date variables contain timestamps, expressed in seconds since Jan 1, 1970, midnight, UTC. A date variable producing the above string in your browser means that at the stored timestamp, it's Apr 20 2020 in your timezone. But a result of 2020-04-20 is not guaranteed, because somebody 10 hours ahead of your time will get 2020-04-21. So yeah, it's complicated. –  Apr 20 '20 at 14:28
  • You might also look at [*Function to convert PHP date format to Javascript date format (not the date itself !)*](https://stackoverflow.com/questions/57279831/function-to-convert-php-date-format-to-javascript-date-format-not-the-date-itse) – RobG Apr 21 '20 at 23:27
  • @drake035—completely agree. The lack of a decent parser or formatter is an indication of how little attention the TC39 is paying to the ECMAScript Date object. Reliance on ECMA-402 (which is horribly clunky and doesn't do parsing) is just a copout, IMHO of course. :-) – RobG Apr 21 '20 at 23:29

0 Answers0