Avoid legacy date-time classes
The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid them. Now supplanted by the java.time classes.
Instant
As others said, a java.util.Date
represents a moment on the timeline in UTC with a resolution of milliseconds. A java.util.Date
has no format at all.
You can convert Date
objects to a java.time.Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myUtilDate.toInstant();
ZonedDateTime
Assign a time zone in which getting a date makes sense in your scenario. A time zone is crucial to determining a date; for any given moment the date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
LocalDate
Now if you want to work with date-only values without a time-of-day and without a time zone, extract a LocalDate
object from the ZonedDateTime
object.
LocalDate ld = zdt.toLocalDate();
Generating strings
To generate a String representing this LocalDate
value in the format you requested, simply call toString
. That format of YYYY-MM-DD is a standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings. Do not confuse a formatted string with the date-time object. A date-time object has no format, only strings have a format.
String output = ld.toString();
If you want other formats, search Stack Overflow for the class DateTimeFormatter
.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.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.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.