Convert String to Date in Java
Java has a dedicated class for representing and manipulating dates. This full package name of this class is java.util.Date. However when we receive date from external sources such as web services, we receive them as a String. The format of this date string depends on the source of the data. Hence we require conversion from String to Date depending on how date is encoded in a String. Java has a utility class called SimpleDateFormat for String to Date conversion.
The following program demonstrates how a String can be converted to a Date class. Note that in this example, the string is assumed to be in the form of “day of the month, full name of the month and full year” (26 September 2015). The pattern for SimpleDateFormat in this case is “d MMMMM yyyy”. Please see this link for the full set of pattern characters available.
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Converting a string to a Java date variable * @author jj */ public class DateConvertor { //See http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html //This pattern string is dependent on how date is represented in String private static final String DATE_STRING_FORMAT="d MMMMM yyyy"; //26 September 2015 public static void main(String[] args) { DateConvertor dc = new DateConvertor(); String dateString = "26 September 2015"; Date date = dc.convert(dateString); System.out.println("Date is "+date); } /** * * @param dateString date in string form * @return date in java.util.Date class */ private Date convert(String dateString) { Date date = null; SimpleDateFormat sdf = new SimpleDateFormat(DATE_STRING_FORMAT); try { date = sdf.parse(dateString); }catch(ParseException px){ System.out.println("Unable to parse date"); } return date; } }