Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  27] [ 3]  / answers: 1 / hits: 15682  / 8 Years ago, thu, march 31, 2016, 12:00:00

Is there a simple way to convert a JavaScript Date to a Java 8 date-time with a time-zone?



I have a web application which consists of two parts, front end is written in JavaScript and the back end in Java. A user should be able to select a date-time in UI and the value should be consumed by the back end. What is the easiest way of converting this value to Java date-time?


More From » java

 Answers
12

You can convert time using The Universal Coordinated Time (UTC) and ZonedDateTime, for example:



Thu, 31 Mar 2016 06:49:02 GMT
Thu, 31 Mar 2016 06:49:02 -0830


JavaScript



var d = new Date();
var n = d.toUTCString();


toUTCString() method converts a Date object to a string, according to universal time. For example, console.log(n); will print out a result:



Tue, 17 Mar 2020 08:59:19 GMT


Java 8



ZonedDateTime zdt = ZonedDateTime.parse(text, DateTimeFormatter.RFC_1123_DATE_TIME);


text is a UTC date and time string

ZonedDateTime is a date-time with a time-zone in the ISO-8601 calendar system

RFC_1123_DATE_TIME is a predefined RFC-1123 date-time formatter.



Printing zdt for the above example value will produce:



2020-03-17T08:59:19Z

[#62749] Monday, March 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harrisa

Total Points: 514
Total Questions: 93
Total Answers: 93

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
;