Java Data Type How to - Parse String "24-10-2012" into Date ( dd-mm-yyyy) format








Question

We would like to know how to parse String "24-10-2012" into Date ( dd-mm-yyyy) format.

Answer

import java.text.SimpleDateFormat;
import java.util.Date;
/*w  w  w.j  av  a  2  s.c  o  m*/
public class Main {
  public static void main(String args[]) {
    Date todaysDate = new java.util.Date();
    // Formatting date into yyyy-MM-dd HH:mm:ss e.g 2015-10-10 11:21:10

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String formattedDate = formatter.format(todaysDate);
    System.out.println("Formatted date is ==>" + formattedDate);

    // Formatting date into yyyy-MM-dd e.g 2015-10-10
    formatter = new SimpleDateFormat("yyyy-MM-dd");
    formattedDate = formatter.format(todaysDate);
    System.out.println("Formatted date is ==>" + formattedDate);

    // Formatting date into MM/dd/yyyy e.g 10/10/2015
    formatter = new SimpleDateFormat("MM/dd/yyyy");
    formattedDate = formatter.format(todaysDate);
    System.out.println("Formatted date is ==>" + formattedDate);
  }
}

The code above generates the following result.