0

Inside my JSON there are three different types of date values:

  • D.M.YYYY
  • DD.M.YYYY
  • D.MM.YYYY.

How would you suggest me to standardize this to YYYY.MM.DD format? (like 2022.02.02 instead of 2.02.2022 or 02.2.2022 or 2.2.2022)?

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • 3
    How about storing a unix timestamp instead? Then you don't have to worry about timezone information either. – Felix Kling May 05 '17 at 20:52
  • 1
    Split, pad with zeroes, join. – PM 77-1 May 05 '17 at 20:55
  • Take a look at http://stackoverflow.com/questions/10286204/the-right-json-date-format – SmartDev May 05 '17 at 20:59
  • Duplicate of [*Reformat string containing date with Javascript*](http://stackoverflow.com/questions/35784911/reformat-string-containing-date-with-javascript)? – RobG May 05 '17 at 21:00
  • Does this answer your question? [convert dd/mm/yyyy to mm/dd/yyyy in javascript](https://stackoverflow.com/questions/5433313/convert-dd-mm-yyyy-to-mm-dd-yyyy-in-javascript) – pilchard Apr 08 '23 at 21:21

1 Answers1

1
dmy="9.8.2034".split("."); 

result = ("0000" + dmy[2]).slice(-4) +"." 
       + ("00" + dmy[1]).slice(-2) +"." 
       + ("00" + dmy[0]).slice(-2);

// result = "2034.08.09"

While this is my general approach, in your case, if you are certain that the D and M fields will definitely always contain at least 1 digit, and the Y field will always be a full 4-digit year, you could chop off some of the extra "0"s you are adding.

result = dmy[2]+"." 
       + ("0" + dmy[1]).slice(-2) +"." 
       + ("0" + dmy[0]).slice(-2);

Personally, however, I would suggest using my more verbose first method above, as it will be easier for you to recognise what your intention was when you are later re-reading your code.

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • You can just [`padStart()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) – pilchard Apr 08 '23 at 21:16