Java - Legacy Date Time Parsing

Introduction

The parsing 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 argument is the starting position of the character in the text.

The following code shows how to parse string to date:

Demo

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 = "09/19/2028";

    // Create a pattern for the 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);

    // Since the date part in text "09/19/2028" 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);
    System.out.println(parsedDate);

  }//from w  w  w .  ja  va 2 s  .  c o  m
}

Result

Related Topics