Parsing Strings into Dates


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


Use a DateFormat.


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.

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); 
} 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:

// SimpleDateFormat formatter = new SimpleDateFormat ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.