Create SimpleDateFormat and format a date


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

public class Main{

  public static void main(String args[]) {
    Date date = new Date();
    SimpleDateFormat sdf;
    sdf = new SimpleDateFormat("hh:mm:ss");
    System.out.println(sdf.format(date));
    sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
    System.out.println(sdf.format(date));
    sdf = new SimpleDateFormat("E MMM dd yyyy");
    System.out.println(sdf.format(date));

  }
}

The output:


10:33:10
30 Oct 2010 10:33:10 PDT
Sat Oct 30 2010

Parsing date string into Date object using SimpleDateFormat


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

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:


Fri Dec 31 00:00:00 PST 2010
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.