Reputation: 445
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:
Upvotes: 6
Views: 606
Reputation: 1717
Ugh - I've run into this problem before.
The SimpleDateFormat.parse(String)
method (I suspect) uses an instance of Calendar
. This matters for two reasons:
These default values are having an impact when the ft.format(t)
call is made. The only way to solve this problem that I've found is to work with the Calendar class directly (which is entirely non-trivial, BTW.) I'll try to provide a code sample later when I've got more time. In the mean time, look at javafx.util.converter.DateStringConverter
.
Upvotes: 0
Reputation: 411
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));
}
}
Upvotes: 1
Reputation: 17422
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)
Upvotes: 4
Reputation: 1509
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.
Upvotes: 1