I have a method which recieves a date as argument in string as following format "20230504". I want to change that date to "2023-05-04".
How can I do this?
I have a method which recieves a date as argument in string as following format "20230504". I want to change that date to "2023-05-04".
How can I do this?
4
Answers
I believe your best course of action would be to change the caller method to ensure the data you are receiving is correctly formatted.
But if that is not possible, you could use something like this
I mean, this is not the best way to do it, since you would have to be sure the length and the format is the same every time.
Anyway, hope it helps
You can try to split the the potential solution into 2 steps:
1.) Extract the day, month and year, and assign them to different variables. I would suggest using the String.protoype.slice method on the given string for this purpose.
2.) Concatenate them together and add "-" in between.
Sample pseudocode:
Unfortunately this solution will always work if the input is always the same length as your example and that we can assume that the input is always in the format "yyyymmdd".
You could use a regular expression:
Using
slice
,map
andjoin