- Published on
Converting a Java LocalDate to a JavaScript Date
- Authors
- Name
- Yair Mark
- @yairmark
The system I work on has an AngularJS front end. We are currently in the process of finishing up a product and as part of that change the front-end hits a Spring REST endpoint which returns an object that contains a LocalDate. So I have something like this:
LocalDate.of(2018, Month.MAY, 15);
This gets passed to the front-end as an array of numbers:
;[2018, 5, 15]
The JavaScript Date
object unfortunately cannot convert this to a date object in this form. Ideally I could use MomentJS but at the point where this is needed I cannot import it. After doing a bit of Googling I saw that the Date
object does accept a String in its constructor but it has to be in ISO format. I did not want to have to add on zeros to a string consisting of this so I tried my luck in the console:
new Date('2018-05-15')
Lo and behold it returns the date as I would have hoped. I went 1 step further and left off the 0
for May so that I can simply concatenate the array together as a string and it works perfectly:
new Date('2018-5-15')
To easily convert this you can using something like the below:
;[2015, 5, 15].map((num) => num + '').join('-')