Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tappoz/8abd050b7fd2905226e963da0913bd63 to your computer and use it in GitHub Desktop.
Save tappoz/8abd050b7fd2905226e963da0913bd63 to your computer and use it in GitHub Desktop.

Java 8 UTC date-time to formatted string and viceversa

// YYYY-MM-DDTHH:mm:ssZ

// date ---> string
java.time.format.DateTimeFormatter.ISO_INSTANT.format(java.time.ZonedDateTime.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS))

// string ---> date
java.time.ZonedDateTime.parse('2016-07-18T13:26:45Z', java.time.format.DateTimeFormatter.ISO_INSTANT.withZone(java.time.ZoneOffset.UTC))

// java.time.ZoneId utcZoneId = java.time.ZoneOffset.UTC
java.time.Instant nowUtc = java.time.Clock.systemUTC().instant()

// alternative
private final LocalDateTime referenceDateTime = LocalDateTime.of(2016, 4, 1, expectedHourOfDay, 0)
private final Clock clockForTests = Clock.fixed(referenceDateTime.atZone(ZoneOffset.UTC).toInstant(), ZoneOffset.UTC);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment