Skip to content

Migrate java.util.Date to java.time.Instant - #1080

Open
JoseCsDev wants to merge 1 commit into
jwtk:mainfrom
JoseCsDev:feature/migrate-to-instant
Open

JoseCsDev wants to merge 1 commit into
jwtk:mainfrom
JoseCsDev:feature/migrate-to-instant

Conversation

@JoseCsDev

@JoseCsDev JoseCsDev commented Oct 3, 2026 •

Copy link
Copy Markdown

Summary

This MR migrates JJWT's internal date/time handling from java.util.Date to java.time.Instant, and adds
Instant-based alternatives to every public API that accepts or returns a Date:

  • Claims, ClaimsMutator, JwtBuilder and JwtParserBuilder (exp, nbf, iat and the require* assertions)
  • Clock
  • DateFormats

The Date variants are deprecated and will be removed before the 1.0 release.

The change is additive and binary compatible. All new interface methods have default implementations, and no
existing signature was removed or changed, so existing Claims, ClaimsMutator, JwtParserBuilder and Clock
implementations keep working. japicmp against 0.13.0 reports only added methods for these types.

The Jackson, Gson and org.json extensions can now also serialize Instant values in custom claims.

Motivation

java.util.Date is widely considered bad practice in modern Java code:

  • It is mutable. JJWT used to return its internal Date instances from getters such as Claims.getExpiration()
    and FixedClock.now(), so callers could change internal state.
  • Its API is confusing. It represents an instant, yet it has a misleading toString() in the JVM's default time
    zone, mostly deprecated calendar methods, and relies on the non-thread-safe SimpleDateFormat for formatting and
    parsing. That is why DateFormats needed ThreadLocal caches, which are never cleaned up in pooled threads.
  • It is error prone. NumericDate conversion (seconds * 1000) and clock skew arithmetic on long millis could
    overflow silently and produce incorrect dates.

java.time.Instant (Java 8+) is immutable, thread-safe, has clear arithmetic and comparison methods, and fails fast
on out-of-range values. JJWT 0.14.0 already requires Java 8, so this is the natural time to move to java.time
while giving users a deprecation period before 1.0.

Changes

Public API (jjwt-api)

  • Claims: new default methods expiration(), notBefore() and issuedAt() returning Instant.
    getExpiration(), getNotBefore() and getIssuedAt() are deprecated.
  • ClaimsMutator and JwtBuilder: new default methods expiration(Instant), notBefore(Instant) and
    issuedAt(Instant). The Date overloads are deprecated, and the setXxx(Date) javadoc now points to the
    Instant variants.
  • JwtParserBuilder: new default methods requireExpiration(Instant), requireNotBefore(Instant) and
    requireIssuedAt(Instant). The Date overloads are deprecated.
  • Clock: new default Instant instant(), which returns now().toInstant(). Date now() is deprecated, but it
    stays the only abstract method until 1.0, so existing implementations and lambdas (() -> new Date()) still
    compile and work.
  • DateFormats:
    • New formatIso8601(Instant), formatIso8601(Instant, boolean) and parseIso8601Instant(String), built on
      immutable, thread-safe DateTimeFormatter instances.
    • formatIso8601(Date, ...) now delegates to the Instant variant.
    • parseIso8601Date keeps its lenient SimpleDateFormat behavior. It now creates a new instance per call instead
      of caching it in a ThreadLocal, which fixes Sonar java:S5164.
    • The Date variants are deprecated.

Implementation (jjwt-impl)

  • New JwtInstantConverter: the converter for RFC 7519 NumericDate values. It reads exp/nbf/iat numbers as
    seconds, and accepts Instant, Date, Calendar, numeric strings and ISO-8601 strings. Out-of-range values
    throw IllegalArgumentException instead of overflowing.
  • Parameters: rfcDate() was replaced by rfc(), which returns a Parameter<Instant>.
  • DefaultClaims:
    • exp, nbf and iat are now stored as Instant.
    • The deprecated Date getters return a new Date copy on each call.
    • get(name, Date.class) converts the stored Instant directly. Without this, the raw value in seconds would be
      read as milliseconds and produce a date in 1970.
    • New support for get(name, Instant.class).
  • DelegatingClaimsMutator, DefaultJwtBuilder and DefaultJwtParserBuilder: the Instant methods hold the
    logic, and the deprecated Date overloads convert their argument and call them. Internal calls to deprecated
    setters were also replaced.
  • DefaultJwtParser:
    • exp/nbf validation now uses only Clock.instant(), truncated to milliseconds so the clock skew logic and the
      error messages stay unchanged.
    • Fixed a long overflow in nbf validation that occurred with a very large allowed clock skew.
    • require(name, Instant) now converts the actual claim value before comparing it. Previously it never matched.
  • DefaultClock: instant() returns Instant.now(), and now() returns Date.from(instant()).
  • FixedClock: stores an Instant internally. Added FixedClock(Instant), deprecated FixedClock(Date), and
    now() returns a new Date copy on each call.
  • JwtDateConverter: reduced to the static toDate(Object) method, which the deprecated
    Claims.get(name, Date.class) path still needs because it parses ISO-8601 strings leniently.

JSON extensions

Instant values in custom claims are serialized as ISO-8601 strings with millisecond precision
(e.g. "2026-10-03T10:00:00.123Z"), the same format used for Date. They can be read back with
Claims.get(name, Instant.class). Before this change, all three extensions threw an exception when serializing an
Instant.

  • jjwt-jackson:
    • New package-private JacksonInstantSerializer and JacksonInstantDeserializer, so jackson-datatype-jsr310 is
      not required. The deserializer also makes JacksonDeserializer claim type maps work with Instant.class.
    • They are registered only on JJWT's default ObjectMapper, never on an application-provided one, so an existing
      JavaTimeModule configuration is not overridden.
  • jjwt-gson: new public GsonInstantTypeAdapter, registered on the default Gson instance. Users with a custom
    Gson instance can register it themselves.
  • jjwt-orgjson: OrgJsonSerializer supports Instant.

Behavior changes (documented in the CHANGELOG)

  • null literal ambiguity: calls such as builder.expiration(null) or new FixedClock(null) no longer compile,
    because both a Date and an Instant overload now exist. Use an explicit cast, e.g. expiration((Instant) null).
    The ambiguity disappears when the Date variants are removed.
  • Out-of-range values: exp, nbf and iat values outside the supported range now fail during parsing instead
    of silently overflowing.
  • IncorrectClaimException.getClaimValue(): returns an Instant for failed exp/nbf/iat assertions, and the
    exception message shows the value in ISO-8601 format.
  • Exception messages: some conversion error messages changed. For example, Cannot create Date from ... is now
    Cannot create Instant from ..., and ISO-8601 parse errors now come from DateTimeFormatter.
  • DateFormats output: formatIso8601(Date) uses the proleptic Gregorian calendar for dates before 1582-10-15,
    and adds a + prefix to years after 9999. Output is unchanged for all other dates.

Build

  • pom.xml:
    • jjwt.previousVersion changed from 0.11.2 to 0.13.0, so the japicmp report only lists changes introduced in
      this release.
    • Added a targeted ignoreMissingClassesByRegularExpressions entry for io.jsonwebtoken.lang.Supplier. That class
      was renamed to ConfidentialValue earlier in 0.14.0, and without this entry japicmp can't load
      jjwt-gson 0.13.0's GsonSupplierSerializer for comparison.

Documentation

  • CHANGELOG.md: new java.time.Instant Support and Behavior Changes sections under 0.14.0.
  • README.adoc:
    • The builder examples use Instant.
    • The Custom Clock Support section was rewritten, including how to implement a Clock.
    • Instant was added to the list of automatically converted claim types.
    • Notes on Instant handling for Jackson and Gson.
    • A note for Android about API level 26+ or Java 8+ API desugaring.

Testing

  • New test classes: JwtInstantConverterTest, DefaultClockTest and GsonInstantTypeAdapterTest.
  • Extended tests:
    • API: ClaimsTest, ClaimsMutatorTest, ClockTest, JwtBuilderTest, JwtParserBuilderTest and
      DateFormatsTest.
    • Implementation: JwtParserTest, DefaultJwtBuilderTest, FixedClockTest and JwtDateConverterTest.
    • Extensions: Jackson, Gson and org.json serializer and deserializer tests.
  • What the tests cover:
    • every new Instant overload;
    • the get("exp", Date.class) regression;
    • a Clock whose now() throws, to verify the parser only calls instant();
    • the clock skew overflow fix;
    • require(name, Instant);
    • DateFormats output identical to the previous SimpleDateFormat implementation;
    • an application ObjectMapper keeping its own Instant handling.
  • Existing Date-based tests were kept, because they cover the deprecated API.
  • Result: ./mvnw clean verify passes, with japicmp enabled, across all modules: api 153, jackson 32, orgjson 66,
    gson 29, impl 1555 and tdjar 20 tests.

Contributed by: Jose Caselles Sanchez from @ Dempo

@JoseCsDev JoseCsDev changed the title Migrate to Intant Migrate java.util.Date to java.time.Instant Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant