2017-04-24 60 views
0

我需要一個UTC時間字符串轉換成我的本地時間,代碼的時候我就運行它的Eclipse,但是,我得到的Android不正確的結果工作在我的電腦罰款。我卡住了,有人可以幫忙。安卓UTC時間轉換問題

下面是我使用的代碼,一個例子輸入是「2017年4月24日1:00 AM」,這將產生「11:00 AM」其結果就是我但是,期待在Android上始終返回「10:00 AM」。

public String convertUTCTime(String utcTime) { 

    Calendar cal = Calendar.getInstance(); 
    TimeZone tz = cal.getTimeZone(); 

    SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm a"); 
    sdf.setTimeZone(TimeZone.getTimeZone("UTC")); 

    try { 
     Date date = sdf.parse(utcTime); 
     sdf = new SimpleDateFormat("HH:mm a"); 
     sdf.setTimeZone(tz); 
     String format = sdf.format(date); 
     return format; 
    } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return "Not applicable"; 
} 
+0

您是否正在考慮節省一天光的可能性 -

public static String getUTCDate(String timestamp, String DateFormat) { SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm aa", Locale.getDefault()); originalFormat.setTimeZone(TimeZone.getTimeZone("GMT")); SimpleDateFormat targetFormat = new SimpleDateFormat(DateFormat, Locale.getDefault()); targetFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = null; String formattedDate = null; try { date = originalFormat.parse(timestamp); formattedDate = targetFormat.format(date); } catch (ParseException e) { e.printStackTrace(); } return formattedDate; } 

通過調用獲得的價值? –

+0

@james使用有效的日期格式來解析你使用的24小時制格式的日期,並且你的理解不適用於https://developer.android.com/reference/java/text/SimpleDateFormat.html鏈接。 –

+0

請把yyyy-MM-dd替換爲HH:mm a到yyyy-MM-dd hh:mm a這會給你有效的結果 –

回答

0

看看我準備的功能: -

Utils.getUTCDate("2017-04-24 01:00 AM", "HH:mm a") 
+0

嘿,謝謝你的回答,但是你的方法對我不起作用,我仍然得到錯誤的輸出。 – james

+0

給我你的意見。確保您的輸入是「2017-04-24 01:00 AM」而不是「2017-04-24 1:00 AM」。 – Wizard

+0

我已經將輸入硬編碼爲「2017-04-24 01:00 AM」,它仍然在android中返回「10:00 am」,在我的個人電腦上運行良好。 – james