简体   繁体   中英

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:

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)

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.

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));
        }
}

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:

  1. You don't know which flavor of Calendar you're dealing with (Gregorian? Mayan? Vegan?).
  2. Calendar initializes its fields with default values that you don't necessarily want set. When the SimpleDateFormat calls getTime() on the Calendar instance it created to return a Date, that Date will have default field values that aren't indicated by the string you submitted to begin with.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM