I have a string with a "bad" formatted date & time which I need to convert to a Date
object so I can format it's contents using the SimpleDateFormat
and the current Locale
.
However, no matter how I try, I can never get the ouput to show the correct time, I convert from a PST time (UTC-8) to GMT, but the printed hour is +1 hour too much, GMT is only +7 from the (currently PDT) timezone.
I've tried the code on two Android devices, one set to GMT and one set to CET, one Android emulator, and running from command-line, all of them get the hour wrong. (+1)
What am I doing wrong in my code below?
String sourceSDFformatter = "MMM d, h:mm a Z";
String destSDFformatter = "EEEEE, MMMMM dd, HH:mm";
String dateString = "Mar 20th, 10:00 AM PST".replaceAll("st|nd|rd|th", "");
SimpleDateFormat sourceSDF = new SimpleDateFormat(sourceSDFformatter, Locale.US);
SimpleDateFormat destSDF = new SimpleDateFormat(destSDFformatter, Locale.UK);
TimeZone sourceTZ = TimeZone.getTimeZone("America/Los_Angeles");
TimeZone destTZ = TimeZone.getTimeZone("GMT");
sourceSDF.setTimeZone(sourceTZ);
destSDF.setTimeZone(destTZ);
Date myDate = sourceSDF.parse(dateString);
myDate.setYear(new Date().getYear());
System.out.println("Your Time: " + destSDF.format(myDate));
Outputs:
Your Time: Wednesday, March 20, 18:00
When my expected output would be: Your Time: Wednesday, March 20, 17:00
.
I've tried the SO answer in Conversion of local time zone to GMT in java and it works perfectly if I change TimeZone.getTimeZone("America/Los_Angeles")
, then the printed hour is +7 hours ahead which is correct.