设置 UTC 时区在 Android 中不起作用

Setting UTC Timezone is not working in Android

我正在尝试使用以下代码将毫秒时间值转换为 UTC 12 小时格式:

    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

            }

        }

这里的值=“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

不知道哪里出了问题

您需要明确使用 DateFormat.setTimeZone() 以在所需时区打印日期。

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

完成后调用它:

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

如果您从服务器接收到的时间不是 UTC 时间,那么您不应将 Calendar 实例设置为 UTC。而是直接设置你的日历时间。
移除

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

并调用

Calendar calendar = Calendar.getInstance();  

您的最终代码应该是这样的:

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

            }

        }