Conversion
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:
- Obtain an instance via one of the
static
get*Instance()
methods inDateFormat
. This is especially useful when you want the format to be in the user’s locale. For example,DateFormat.getDateInstance(DateFormat.SHORT)
. - Create your very own specific format by creating an instance of
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.
Notes:
- That you’re working in Eclipse doesn’t matter to the problem.
References
- ISO 8601 https://en.wikipedia.org/wiki/ISO_8601
- RFC 1123 https://www.ietf.org/rfc/rfc1123.txt
DateFormat
https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.htmlSimpleDateFormat
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html- Java 8
java.time
package https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
solved convert String to Util date in “dd-MMM-yyyy” fromat [duplicate]