Java Reference
In-Depth Information
// Create simple date format
SimpleDateFormat simpleFormatter = new SimpleDateFormat(pattern);
// Print the date
System.out.println(simpleFormatter.format(birthDate));
I was born on the Day 19 of the month September in 1969
So far, you have converted date objects into formatted text. Let's look at converting text into Date objects. This is
accomplished by using the parse() method of the SimpleDateFormat class. The signature of the parse() method is
as follows:
public Date parse(String text, ParsePosition startPos)
The parse() method takes two arguments. The first argument is the text from which you want to extract the date.
The second one is the starting position of the character in the text from where you want to start parsing. The text can
have date part embedded in it. For example, you can extract two dates from text such as “First date is 01/01/1995 and
second one is 12/12/2001”. Because the parser does not know where the date begins in the string, you need to tell it
using the ParsePosition object. It simply keeps track of the parsing position. There is only one constructor for the
ParsePosition class and it takes an integer, which is the position where parsing starts. After the parse() method is
successful, the index for the ParsePosition object is set to the index of the last character of the date text used plus
one. Note that the method does not use all the text passed as its first argument. It uses only the text as necessary to
create a date object. Let's start with a simple example. Suppose you have a string of “09/19/1969”, which represents the
date September 19, 1969. You want to get a date object out of this string. The following snippet of code illustrates the
steps:
// Our text to be parsed
String text = "09/19/1969";
// Create a pattern for the date text "09/19/1969"
String pattern = "MM/dd/yyyy";
// Create a simple date format object to represent this pattern
SimpleDateFormat simpleFormatter = new SimpleDateFormat(pattern);
// Since the date part in text "09/19/1969" start at index zero
// we create a ParsePosition object with value zero
ParsePosition startPos = new ParsePosition(0);
// Parse the text
Date parsedDate = simpleFormatter.parse(text, startPos);
// Here, parsedDate will have September 19, 1969 as date and startPos current index will be set to
10, which you can get calling startPos.getIndex() method.
Let's parse more complex text. If the text in the previous example were “09/19/1969 Junk”, you would have gotten
the same result, because after reading 1969, the parser will not look at any more characters in the text. Suppose you
have text “XX01/01/1999XX12/31/2000XX”. There are two dates embedded in the text. How would you parse these two
dates? Note that the text for the first date starts at index 2 (the first two Xs have indices 0 and 1). Once parsing is done
 
Search WWH ::




Custom Search