text
Convert String to Date with DateFormat
This is an example of how to convert a String to Date with DateFormat. As the Java API documentation states Date formats are not synchronized, so it is recommended to create separate format instances for each thread. Below are three examples of creating separate instances of DateFormat.
- The “getDateInstance(..)” approach implies that you should invoke the
getDateInstance(int style)
API method, with a specific formatting style in order to create a new instance of DateFormat. Then invoke theparse(String source)
API method, using a String to produce a Date. - In “synchronization” approach, you should create a new SimpleDateFormat, with a given pattern. Lock the dateformat in a synchronized statement and use it to parse a String, with
parse(String source)
API method. - The “ThreadLocal” approach uses a ThreadLocal for the DateFormat. We can override the
initialValue()
API method of the ThreadLocal to set an initial value to the threadlocal. Then we can use theget()
API method to return the current thread’s value of this dateformat and use theparse(String source)
API method of the DateFormat to parse a String and produce a Date.
Let’s take a look at the code snippets that follow:
package com.javacodegeeks.test; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ConcurrentDateFormatAccess { public Date convertStringToDate(String dateString) throws ParseException { return SimpleDateFormat.getDateInstance(DateFormat.MEDIUM).parse(dateString); } }
package com.javacodegeeks.test; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ConcurrentDateFormatAccess { private DateFormat df = new SimpleDateFormat("yyyy MM dd"); public Date convertStringToDate(String dateString) throws ParseException { Date result; synchronized(df) { result = df.parse(dateString); } return result; } }
package com.javacodegeeks.test; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ConcurrentDateFormatAccess { private ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat> () { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy MM dd"); } }; public Date convertStringToDate(String dateString) throws ParseException { return df.get().parse(dateString); } }
Related Article:
This was an example of how to convert String to Date with DateFormat in Java.