Search code examples
androiddatetimeandroid-studiotimezoneandroid-timepicker

How to convert time as per Timezone selection in android?


My Application downloading shopping details.
Example : Shopping details downloaded at 5 :30 London time.
Now, change any other timezone, so convert downloaded time s per the selected timezone.
Timezone is changing from settings under Date/time. How to programmatically achieve this ? so how to convert the downloaded time as per the timezone selection ?


Solution

  • Try this,

    I assume you have downloaded the shopping details at 12:00 PM London time. I am using HH assuming that you are using 24hr format. If you want to convert that to device default time zone, set the timezone using DateFormat & format the existing time.

    TimeZone.getDefault() which gives the device default timezone.

     try {
           DateFormat utcFormat = new SimpleDateFormat("HH:mm");
           utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    
           Date date = utcFormat.parse("12:00");
    
           DateFormat deviceFormat = new SimpleDateFormat("HH:mm");
           deviceFormat.setTimeZone(TimeZone.getDefault()); //Device timezone
    
           String convertedTime = deviceFormat.format(date);
    
    } catch(Exception e){
    
    }