Parse date string into Date object

In this chapter you will learn:

  1. How to parse date string
  2. Convert date string from one format to another format using SimpleDateFormat

Parse date string

The following code creates a SimpleDateFormat object and specifies the pattern for SimpleDateFormat. Then it parses date string into Date object using SimpleDateFormat

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/*from   j  a  v  a 2  s. c  om*/
public class Main {
  public static void main(String[] args) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
    try {
       Date date = sdf.parse("31/12/10");
      System.out.println(date);
    } catch (ParseException pe) {
      System.out.println("Parse Exception : " + pe);
    }
  }
}

The output:

Convert date string from one format to another format using SimpleDateFormat

The following code converts date string from one format to another format using SimpleDateFormat. It creates two objects of SimpleDateFormat. One is used as a parser and the other is uses as formatter. It converts the string value to date value in the first step and convert the date value to the target format in the second step.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/* jav  a2  s  .  com*/
public class Main {
  public static void main(String[] args) throws ParseException {
    String strDate = "30/12/99";

    SimpleDateFormat source = new SimpleDateFormat("dd/MM/yy");

    Date date = source.parse(strDate);

    SimpleDateFormat target = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");

    strDate = target.format(date);
    System.out.println("Converted date is : " + strDate);

  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Formatting day using SimpleDateFormat
  2. Formatting day of week using SimpleDateFormat