tl;dr
myGregCal.toZonedDateTime()
.toInstant()
…or…
java.util.Date.from(
myGregCal.toZonedDateTime()
.toInstant()
)
java.time
My goal is to take a Calendar I receive as parameter from other code and get a UTC (java.util) Date for further use.
The troublesome old date-time classes of Calendar
and Date
are now legacy, supplanted by the java.time classes. Fortunately you can convert to/from java.time by calling new methods on the old classes.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;
For UTC value, extract an Instant
. That class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = zdt.toInstant() ;
To generate a String representing that UTC value in a standard ISO 8601 format, call toString
.
String output = instant.toString() ;
If you need other formats in generated strings, convert to the more flexible OffsetDateTime
and use DateTimeFormatter
. Search Stack Overflow for many examples.
Best to avoid the Date
class. But if you must, convert. Like Instant
, Date
represents a point on the timeline in UTC. But Date
is limited to milliseconds resolution. So you risk data loss, lopping off digits from the decimal fraction of a second beyond the 3 digits of milliseconds versus 9 digits of nanoseconds.
java.util.Date utilDate = Date.from( instant ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.