user818455 user818455 - 14 days ago 6
Android Question

Setting UTC Timezone is not working in Android

I am trying to convert millisecond time value to UTC 12 hour format using following code:

public void updateDateAndTimeForMumbai(String value) {
SimpleDateFormat outputTimeFormatter = new SimpleDateFormat("h:mm");
SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

try {
calendar.setTimeInMillis(Long.parseLong(value));
Log.i("Scheduled date: " + outputDateFormatter.format(calendar.getTime()));
Log.i("Scheduled time: " + outputTimeFormatter.format(calendar.getTime()));
Log.i("Scheduled time Am/Pm: " + new SimpleDateFormat("aa").format(calendar.getTime()));

} catch (NumberFormatException n) {
//do nothing and leave all fields as is

}

}


Here value = "1479633900000"

Output is:
Scheduled date: 20/11/2016
Scheduled time: 2:55
Scheduled time Am/Pm: AM

What I want is:
Scheduled date: 20/11/2016
Scheduled time: 9:25
Scheduled time Am/Pm: AM


I don't know where is the problem.

Answer

You need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.

outputDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));

Call this after you do :

SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");

If the time you are receiving from server is not UTC time, then you shouldn't set your Calendar instance to UTC. but just directly set your Calendar time.
Remove

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));  

And call

Calendar calendar = Calendar.getInstance();  

Here is how should look your final code :

public void updateDateAndTimeForMumbai(String value) {
            SimpleDateFormat outputTimeFormatter = new SimpleDateFormat("h:mm");
            outputTimeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
            SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
            outputDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));

            // Create a calendar object that will convert the date and time value in milliseconds to date.
            Calendar calendar = Calendar.getInstance();

            try {
                calendar.setTimeInMillis(Long.parseLong(value));
                Log.i("Scheduled date: " + outputDateFormatter.format(calendar.getTime()));
                Log.i("Scheduled time: " + outputTimeFormatter.format(calendar.getTime()));
                Log.i("Scheduled time Am/Pm: " + new SimpleDateFormat("aa").format(calendar.getTime()));

            } catch (NumberFormatException n) {
                //do nothing and leave all fields as is

            }

        }
Comments