I have a String
representation of a date that I need to create a Date
or Calendar
object from. I've looked through Date
and Calendar
APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Try this:
The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original
java.util.Date
/java.util.Calendar
classes.Joda's
DateFormatter
can parse a String to a JodaDateTime
.In brief:
See
SimpleDateFormat
javadoc for more.And to turn it into a
Calendar
, do:tl;dr
java.time
Java 8 and later has a new java.time framework that makes these other answers outmoded. This framework is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See the Tutorial.
The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them.
LocalDate
Like Joda-Time, java.time has a class
LocalDate
to represent a date-only value without time-of-day and without time zone.ISO 8601
If your input string is in the standard ISO 8601 format of
yyyy-MM-dd
, you can ask that class to directly parse the string with no need to specify a formatter.The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values.
Formatter
If you have a different format, specify a formatter from the java.time.format package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a
Locale
specifying a human language for translation and cultural norms for deciding issues such as period versus comma.Formatting pattern
Read the
DateTimeFormatter
class doc for details on the codes used in the format pattern. They vary a bit from the old outmodedjava.text.SimpleDateFormat
class patterns.Note how the second argument to the
parse
method is a method reference, syntax added to Java 8 and later.Dump to console.
Localize automatically
Or rather than specify a formatting pattern, let java.time localize for you. Call
DateTimeFormatter.ofLocalizedDate
, and be sure to specify the desired/expectedLocale
rather than rely on the JVM’s current default which can change at any moment during runtime(!).Dump to console.
The
DateFormat
class has aparse
method.See http://java.sun.com/j2se/1.4.2/docs/api/java/text/DateFormat.html for more information.