I am trying to convert PST time to Device local time using below function. It works fine but in London timezone its not working properly. If its 04:58 AM PST then it should show 12:58 PM as per London timezone but its showing 12:58 AM. Am i doing anything wrong here? Please kindly guide.
System.out.println("2015-06-23 04:58:00 AM = "
+ getFormattedTimehhmm(new TimeTest()
.getTimeRelativeToDevice("2015-06-23 04:58:00 AM")));
public String getTimeRelativeToDevice(String pstTime) {
final String DATE_TIME_FORMAT = "yyyy-MM-dd hh:mm:ss a";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
TimeZone fromTimeZone = TimeZone.getTimeZone("America/Los_Angeles");
TimeZone toTimeZone = TimeZone.getTimeZone("Europe/London");
// Get a Calendar instance using the default time zone and locale.
Calendar fromCalendar = Calendar.getInstance();
// Set the calendar's time with the given date
fromCalendar.setTimeZone(fromTimeZone);
try {
fromCalendar.setTime(sdf.parse(pstTime));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Input: " + fromCalendar.getTime() + " in "
+ fromTimeZone.getDisplayName());
return sdf.format(fromCalendar.getTime());
}
I agree with Moritz that using Joda Time would make the code simpler, but you should be able to do all of this much more simply than your current approach:
public String getTimeRelativeToDevice(String pstTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date parsed = sdf.parse(pstTime);
sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
return sdf.format(parsed);
}
Currently you're doing all kinds of messing around, but never specifying the time zone of the SimpleDateFormat
, which is the important part...
See more on this question at Stackoverflow