tl;dr
LocalDate.parse(
"01-23-2017" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)
Details
I have a java.util.Date in the format yyyy-mm-dd
As other mentioned, the Date
class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.
java.time
The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.
If you have a java.util.Date
, convert to a Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
Time zone
The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.
Define the time zone by which you want context for your Instant
.
ZoneId z = ZoneId.of( "America/Montreal" );
Apply the ZoneId
to get a ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( z );
LocalDate
If you only care about the date without a time-of-day, extract a LocalDate
.
LocalDate localDate = zdt.toLocalDate();
To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString
. The java.time classes use the standard formats by default when generating/parsing strings.
String output = localDate.toString();
2017-01-23
If you want a MM-DD-YYYY format, define a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );
Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm
(minute of hour) rather than MM
(month of year).
Use the same DateTimeFormatter
object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.
LocalDate localDate = LocalDate.parse( "01-23-2017" , f );
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 the java.time classes.
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.
yyyy-mm-dd
. – Jeana