Java Data Type How to - Parse a Formatted String into Date object in Java








Question

We would like to know how to parse a Formatted String into Date object in Java.

Answer

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
//from www  . java  2s  .  c  o  m
public class Main {
  public static void main(String[] args) throws Exception {
    String dStr = "Wed, 05 Jun 2015 00:48:12 GMT";
    SimpleDateFormat ft = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
    Date t = ft.parse(dStr);
    TimeZone gmt = TimeZone.getTimeZone("England/London");
    ft.setTimeZone(gmt);
    System.out.println(t);
    System.out.println(ft.format(t));
  }
}

The code above generates the following result.