Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a Formatted String into Date object in Java

In Java, How to parse "Wed, 05 Jun 2013 00:48:12 GMT" into a Date object, then print the date object out in the same format.

I have tried this:

String dStr= "Wed, 05 Jun 2013 00:48:12 GMT"; 
SimpleDateFormat ft =  new SimpleDateFormat ("E, dd MMM yyyy hh:mm:ss ZZZ"); 
Date t = ft.parse(dStr); 
System.out.println(t); 
System.out.println(ft.format(t));

The result is

Wed Jun 05 10:48:12 EST 2013
Wed, 05 Jun 2013 10:48:12 +1000 

Thanks in advance:

like image 406
user1304846 Avatar asked Aug 13 '13 22:08

user1304846


3 Answers

You don't have an error, both: Wed, 05 Jun 2013 00:48:12 GMT and Wed, 05 Jun 2013 00:48:12 GMT represent the same time, the first one is GMT (Grenweech) and the second one is the same time in Australia (EST), you just need to configure your time zone properly.

If you want to print the same date in GMT, add this line to your code:

ft.setTimeZone(TimeZone.getTimeZone("GMT"));

Now, if you also want your date to be printed with the time-zone as "GMT" instead of "+0000", follow @HewWolff answer (use zzz instead of ZZZ)

like image 133
morgano Avatar answered Oct 10 '22 22:10

morgano


This solves your problem:

import java.text.*;
import java.util.*;

public class DateIt{
    public static void main(String [] args) throws Exception{
        String dStr= "Wed, 05 Jun 2013 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));
        }
}
like image 1
Clocks Avatar answered Oct 11 '22 00:10

Clocks


It looks like you want zzz rather than ZZZ. That should help you read/write your time zone as a code rather than a number.

like image 1
Hew Wolff Avatar answered Oct 10 '22 23:10

Hew Wolff