Last active
July 10, 2019 15:50
-
-
Save jocafi/322647348ebd6a5bb01dff81285da99d to your computer and use it in GitHub Desktop.
Date/Time Java <=> JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# You can configure the date format and timezone used by Spring which uses in the background Jackson2. | |
# | |
# Normally, you do not have to change nothing in the JavaScript code that run on the browsers around the world. | |
# It will use JSON.stringify() to serialize the date which will be sent in the UTC timezone to the server (Java on backend). | |
# Example: 2018-11-29T14:03:27.281Z | |
# | |
# However, if you are having problems, try to set the values below in your application.properties file for the Spring application. | |
# | |
# Visit the Spring documentation for more information: | |
# https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html | |
# | |
# JACKSON (JacksonProperties) | |
spring.jackson.time-zone: UTC | |
# That property is only used for the java.util.Date | |
# according to https://stackoverflow.com/questions/43622259/how-to-use-spring-boots-spring-jackson-date-format-property | |
spring.jackson.date-format=yyyy-MM-dd'T'HH:mm:ss.SSSXXX |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let myDate = new Date(); | |
JSON.stringify(myDate); | |
// produces for example: | |
// 2018-12-07T20:41:03.345Z |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// It works only using Java SDK 8+ | |
class MyDatetime { | |
/** | |
* Convert a date as string generated by JavaScript using the command JSON.stringify() | |
* to a Java Date. | |
* | |
* @param sDate date to be converted. Ex: 2018-11-29T14:03:27.281Z | |
* @return Java Date | |
*/ | |
Date convertJavaScriptDate(String sDate) { | |
ZonedDateTime zdt = ZonedDateTime.parse(sDate, DateTimeFormatter.ISO_OFFSET_DATE_TIME); | |
Date date = Date.from(zdt.toInstant()); | |
return date; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment