0

I am trying to convert GMT time to local device time zone.But the GMT time

    String res;
    TimeZone tz = TimeZone.getDefault();
    String strTimeZone = tz.getDisplayName(false, TimeZone.SHORT);

    SimpleDateFormat sdfgmt = new SimpleDateFormat("HH:mma");
    sdfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfmad = new SimpleDateFormat("HH:mma");
    sdfmad.setTimeZone(TimeZone.getTimeZone(strTimeZone));

    String inpt = "09:00am";
    Date inptdate = null;
    try {
        inptdate = sdfgmt.parse(inpt);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println("GMT:\t\t" + sdfgmt.format(inptdate));
    System.out.println("Current Time:\t" + sdfmad.format(inptdate));
    res = sdfmad.format(inptdate);

GMT time returns as 00:00am.I cant convert the 9:00am gmt time to local device time zone(GMT+5:30)

Akatosh
  • 448
  • 9
  • 17
Kalai
  • 469
  • 2
  • 9
  • 20

1 Answers1

0

Try this:

String inpt = "09:00amZ";
Date date = null;
try {
    date = new SimpleDateFormat("HH:mmaX").parse(inpt);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mma");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println(sdf.format(date));

Be sure to add a "Z" at the end of the input to tell that this time is in GMT time zone.

If you need a default to the device time zone instead of hardcode replace the sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); by sdf.setTimeZone(TimeZone.getDefault());

sergiomse
  • 775
  • 12
  • 18