Java Reference
In-Depth Information
Converting Script Dates to Java Dates
How will you create a date object in Java such as a java.time.LocalDate object from
a script Date object? Converting a script date to a Java date is not straightforward.
Both types of dates have one thing in common: they work with the same epoch, that is,
midnight on January 1, 1970 UTC. You will need to get the milliseconds in the JavaScript
date elapsed since the epoch, create an Instant , and create a ZonedDateTime from the
Instant . Listing 12-10 contains a complete program to demonstrate the date conversion
between JavaScript and Java. You may get a different output when you run this program.
In the output, the string form of the JavaScript date does not contain milliseconds part,
whereas the Java counterpart does. However, both dates internally represent the
same instant.
Listing 12-10. Converting Script Dates to Java Dates
// ScriptDateToJavaDate.java
package com.jdojo.script;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
public class ScriptDateToJavaDate {
public static void main(String[] args) {
// Get the Nashorn script engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
try {
// Create a Date object in script
ScriptObjectMirror jsDt = (ScriptObjectMirror)
engine.eval("new Date()");
// Get the string representation of the script date
String jsDtString = (String) jsDt.callMember("toString");
System.out.println("JavaScript Date: " + jsDtString);
// Get the epoch milliseconds from the script date
long jsMillis = ((Number) jsDt.
callMember("getTime")).longValue();
// Convert the milliseconds from JavaScript date to
// java Instant
Instant instant = Instant.ofEpochMilli(jsMillis);
 
Search WWH ::




Custom Search