Java - Parse two date value from one string


Suppose you have text "XX01/01/1999XX12/31/2000XX".

There are two dates embedded in the text.

The text for the first date starts at index 2 (the index starts at 0).

Once parsing is done for the first date text, the ParsePosition object will point to the third X in the text.

You can increment its index by two to point to the first character of the second date text.

The following code shows how to Parse two date value from one string:


import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
  public static void main(String[] args) {
    // Our text to be parsed
    String text = "XX01/01/1999XX12/31/2000XX";

    // Create a pattern for our date text "09/19/2028"
    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);

    // To set its index to the next date increment its index by 2.
    int currentIndex = startPos.getIndex();
    int nextIndex = currentIndex + 2;
    startPos.setIndex(nextIndex);/*www.  j  a va  2  s .co  m*/

    // Parse the text to get the second date (December 31, 2000)
    Date secondDate = simpleFormatter.parse(text, startPos);



Related Topic