Skip to content

Commit

Permalink
Adds java.time helpers, fixes 394
Browse files Browse the repository at this point in the history
Instead of migrating to the java.time API we provide helpers to use it directly.
  • Loading branch information
botic committed Jul 16, 2019
1 parent 840d239 commit 753d9f2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
30 changes: 29 additions & 1 deletion modules/ringo/utils/dates.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ export(
"resetDate",
"toISOString",
"fromUTCDate",
"parse"
"parse",
"toInstant",
"toOffsetDateTime"
);

/**
Expand Down Expand Up @@ -847,3 +849,29 @@ function parse(str, format, locale, timezone, lenient) {
}
return date;
}

/**
* Converts the given date to a <code>java.time.Instant</code> instance. Helps to interact with the
* <code>java.time</code> API for dates, times, and durations.
*
* @param date {Date} the JavaScript Date object to convert
* @return {java.time.Instant} instant instance at the given point in time
* @see <a href="https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html">java.time</a>
*/
function toInstant(date) {
return java.time.Instant.ofEpochMilli(date.getTime());
}

/**
* Converts the given date to a <code>java.time.OffsetDateTime</code> instance using the date's offset.
* Helps to interact with the <code>java.time</code> API for dates, times, and durations.
*
* @param date {Date} the JavaScript Date object to convert
* @return {java.time.OffsetDateTime} time instance with offset representing the given date
* @see <a href="https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html">java.time</a>
*/
function toOffsetDateTime(date) {
return java.time.Instant.ofEpochMilli(date.getTime()).atOffset(
java.time.ZoneOffset.ofTotalSeconds(date.getTimezoneOffset() * -60)
);
}
11 changes: 11 additions & 0 deletions test/ringo/utils/dates_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,17 @@ exports.testToISOString = function() {
assert.strictEqual(dates.toISOString(d), "2010-01-02T02:03:04.005Z")
};

exports.testJavaTime = function() {
const d = new Date(Date.UTC(2010, 0, 2, 12, 0, 0, 0));
const formatter = java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME;
const instant = dates.toInstant(d);

const dt = java.time.ZonedDateTime.ofInstant(instant, java.time.ZoneId.of("+02:30"));
assert.strictEqual(dt.format(formatter), "2010-01-02T14:30:00+02:30");

assert.strictEqual(dates.toOffsetDateTime(d).getOffset().getTotalSeconds() / -60, (new Date()).getTimezoneOffset());
};

if (require.main === module) {
require('system').exit(require("test").run(module.id));
}

0 comments on commit 753d9f2

Please sign in to comment.