Converting PST time to Local device time in android

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

-------------Problems Reply------------

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

Date parsed = sdf.parse(pstTime);
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...

You should use jodatime. It greatly simpliefies the time zone conversion. For example:

new LocalDateTime(timestamp.getTime()).toDateTime(DateTimeZone.UTC);

Category:android Views:4 Time:2019-02-02

Related post

Copyright (C), All Rights Reserved.

processed in 0.108 (s). 11 q(s)