I want to convert String
to Date
in different formats.
For example,
I am getting from user,
String fromDate = "19/05/2009"; // i.e. (dd/MM/yyyy) format
I want to convert this fromDate
as a Date object of "yyyy-MM-dd"
format
How can I do this?
tl;dr
Details
The other Answers with
java.util.Date
,java.sql.Date
, andSimpleDateFormat
are now outdated.LocalDate
The modern way to do date-time is work with the java.time classes, specifically
LocalDate
. TheLocalDate
class represents a date-only value without time-of-day and without time zone.DateTimeFormatter
To parse, or generate, a String representing a date-time value, use the
DateTimeFormatter
class.Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as
LocalDate
, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.
Dump to console.
See in action in IdeOne.com.
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
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.Take a look at
SimpleDateFormat
. The code goes something like this:A
Date
object has no format, it is a representation. The date can be presented by aString
with the format you like.E.g. "
yyyy-MM-dd
", "yy-MMM-dd
", "dd-MMM-yy
" and etc.To acheive this you can get the use of the
SimpleDateFormat
Try this,
This outputs : 2009-05-19
Convert a string date to java.sql.Date
Use the
SimpleDateFormat
class:Usage:
For efficiency, you would want to store your formatters in a hashmap. The hashmap is a static member of your util class.
While
SimpleDateFormat
will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.