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

时间:2016-11-20 09:49:02

标签: android timezone simpledateformat

我正在尝试使用以下代码将毫秒时间值转换为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

我不知道问题出在哪里。

1 个答案:

答案 0 :(得分:1)

您需要明确使用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

            }

        }