Parsing Strings into Dates

Problem

You need to convert user input into Date or Calendar objects.

Solution

Use a DateFormat.

Discussion

The DateFormat class introduced in Section 6.3 has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given DateFormat object.

// DateParse1.java 
SimpleDateFormat formatter 
    = new SimpleDateFormat ("yyyy-MM-dd"); 
String input = args.length == 0 ? "1818-11-11" : args[0]; 
System.out.print(input + " parses as "); 
Date t; 
try { 
    t = formatter.parse(input); 
    System.out.println(t); 
} catch (ParseException e) { 
    System.out.println("unparseable using " + formatter); 
}

This will parse any date back to Year Zero and well beyond Year 2000.

What if the date is embedded in an input string? You could, of course, use the string’s substring( ) method to extract it, but there is an easier way. The ParsePosition object from java.text is designed to represent (and track) the position of an imaginary cursor in a string. Suppose we have genealogical data with input strings representing the times of a person’s life:

BD: 1913-10-01 Vancouver, B.C. 
DD: 1983-06-06 Toronto, ON

This lists one person’s birth date (BD) and place, and death date (DD) and place. We can parse these using String.indexOf(' ') to find the space after the : character, DateFormat parse() to parse the date, and String.substring( ) to get the city and other geographic information. Here’s how:

// DateParse2.java SimpleDateFormat formatter = new SimpleDateFormat ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.