I am working in Eclipse . I have string date = "12-DEC-2016"
now i want to convert it into util date in same format. Please help me with this query.
I am working in Eclipse . I have string date = "12-DEC-2016"
now i want to convert it into util date in same format. Please help me with this query.
To convert a String
into a java.util.Date
of a specific format, you can use a java.text.DateFormat
. DateFormat
objects can perform conversions in both directions, from String
to Date
by calling format()
and from Date
to String
by calling parse()
. DateFormat
objects can be obtained in multiple ways, here are some:
static
get*Instance()
methods in DateFormat
. This is especially useful when you want the format to be in the user's locale. For example, DateFormat.getDateInstance(DateFormat.SHORT)
.SimpleDateFormat
. For example, new SimpleDateFormat("dd-MMM-yyyy")
You should consider whether you need a particular fixed format or whether you need the format of whatever the user's locale uses. Keep in mind that different countries use different formats.
In case the format is not for a user, but for machine to machine data interchange, you should consider using ISO 8601 or RFC 1123 as a format.
Also consider using the java.time
package instead of java.util.Date
. The java.time
package is more powerful in case you need to perform calculations. It usually leads to code which is easier to understand and more precise, especially regarding the handling of time zones, daylight savings, local time vs. UTC and such.
DateFormat
https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.htmlSimpleDateFormat
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.htmljava.time
package https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.htmlThe accepted Answer by Hujer is correct but focuses on the troublesome outmoded classes of java.data.Date/.Calendar & SimpleDateFormat. As suggested, you should be using the java.time framework built into Java 8 and later.
LocalDate
The new classes include LocalDate
to represent a date-only value, without time-of-day or time zone.
Parsing requires a Locale
when your string includes words to be translated, name of day or month. Better to specify explicitly than depend on JVM’s current default Locale.
String input = "12-DEC-2016";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d-MM-uuuu" );
f = f.withLocale( Locale.ENGLISH );
LocalDate ld = LocalDate.parse( input , f );