2016-11-20 15 views
0

工作,我嘗試使用下面的代碼,以毫秒時間值轉換爲UTC12小時格式:設置UTC的時區不是在Android的

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

您需要明確地使用DateFormat.setTimeZone()打印所需時區中的日期。

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

調用此之後你做的:

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

如果從服務器接收的時間不UTC時間,那麼你應該不是你的日曆實例設置爲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 

      } 

     } 
+0

它不工作,我仍然得到同樣的結果 – user818455

+0

我剛剛編輯我的答案。 – HelloSadness