How to parse a formatted String object in Date in Java

In Java, how to parse "Wednesday, June 05, 2013 00:48:12 GMT" into a Date object, and then print the date object in the same format.

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

Result -

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

Thank you in advance:

+6
source share
4 answers

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)); } } 
+1
source

You have no mistake, both: Wed, 05 Jun 2013 00:48:12 GMT and Wed, 05 Jun 2013 00:48:12 GMT represent the same time, the first is GMT (Grenweech), and the second at the same Time in Australia (EST), you just need to set your time zone correctly.

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 printed with a time zone as "GMT" instead of "+0000", follow @HewWolff's answer (use zzz instead of ZZZ)

+4
source

It looks like you want zzz , not zzz . This should help you read / write your time zone as a code, not a number.

+1
source

Uh - I used to run into this problem.

The SimpleDateFormat.parse(String) method (I suspect) uses a Calendar instance. This matters for two reasons:

  • You do not know what taste of the Calendar do you mean (Gregorian Maya? Vegan?).
  • The calendar initializes its fields with a default value that you do not necessarily want to set. When SimpleDateFormat calls getTime () on the calendar instance that it created to return the date, that date will have default field values ​​that are not indicated by the string you sent to start.

These default values ​​affect the ft.format(t) call. The only way to solve this problem that I found is to work with the Calendar class directly (which is completely nontrivial, BTW.) I will try to provide a sample code later when I have more time. At the same time, look at javafx.util.converter.DateStringConverter .

0
source

Source: https://habr.com/ru/post/951676/


All Articles