Java Reference
In-Depth Information
for the first date text, the ParsePosition object will point to the third X in the text. You just need to increment its index
by two to point to the first character of the second date text. The following snippet of code illustrates the steps:
// Our text to be parsed
String text = "XX01/01/1999XX12/31/2000XX";
// Create a pattern for our 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);
// Set the start index at 2
ParsePosition startPos = new ParsePosition(2);
// Parse the text to get the first date (January 1, 1999)
Date firstDate = simpleFormatter.parse(text, startPos);
// Now, startPos has its index set after the last character of the first date parsed.
// To set its index to the next date increment its index by 2.
int currentIndex = startPos.getIndex();
int nextIndex = currentIndex + 2;
startPos.setIndex (nextIndex);
// Parse the text to get the second date (December 31, 2000)
Date secondDate = simpleFormatter.parse(text, startPos);
It is left to the readers, as an exercise, to write a program that will extract the date in a date object from the
text “I was born on the day 19 of the month September in 1969”. The date extracted should be September 19, 1969.
(Hint: You already have the pattern for this text in one of the previous examples, when you worked on formatting
date objects.)
Here's one more example of parsing text that contains date and time. Suppose you have the text “2003-04-03
09:10:40.325”, which represents a timestamp in the format year-month-day hour:minute:second.millisecond. You
want to get the time parts of the timestamp. Listing 13-2 shows how to get time parts from this text.
Listing 13-2. Parsing a Timestamp to Get Its Time Parts
// ParseTimeStamp.java
package com.jdojo.format;
import java.util.Date;
import java.util.Calendar;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
public class ParseTimeStamp {
public static void main(String[] args){
String input = "2003-04-03 09:10:40.325";
// Prepare the pattern
String pattern = "yyyy-MM-dd HH:mm:ss.SSS" ;
 
Search WWH ::




Custom Search