You are using troublesome old date-time classes now supplanted by the java.time classes.
Wrong input data
Your first example string is incorrect, as the 21st is a Monday not a Tuesday. The second example string with 22nd is correct, and used in my example code below.
Using java.time
Avoid using this kind of format for textual representations of date-time values. In particular, never use the 3-4 letter abbreviation such as EST
or IST
seen in this kind of format, as they are not true time zones, not standardized, and not even unique(!). Specify a proper time zone name. In this particular case, java.time is able to translate that as GMT
as UTC, but other values may fail.
String input = "Tue May 22 14:52:00 GMT 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd HH:mm:ss z uuuu" ).withLocale ( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );
System.out.println ( "zdt: " + zdt );
Dump to console. The toString
method generates a String in standard ISO 8601 format, extended by appending the name of the zone in brackets. These standard formats are a much better choice for when you need to serialize date-time values to text.
System.out.println ( "zdt: " + zdt );
zdt: 2012-05-22T14:52Z[GMT]
Generate String
You can generate a String to represent this value in any format you desire. Generally best to let java.time localize automatically using a Locale
and DateTimeFormatter
.
Your desired format uses a medium-length style for the date portion but a short-length style for the time-of-day portion. Fortunately the DateTimeFormatter
allows you to localize each portion separately, as seen here where we pass a pair of FormatStyle
objects.
Locale l = Locale.US; // Or Locale.CANADA_FRENCH, or Locale.ITALY, etc.
DateTimeFormatter fOutput = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.MEDIUM , FormatStyle.SHORT ).withLocale ( l );
String output = zdt.format ( fOutput );
Dump to console.
System.out.println ( "zdt: " + zdt + " | output: " + output );
zdt: 2012-05-22T14:52Z[GMT] | output: May 22, 2012 2:52 PM
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.