2015-06-25 57 views
2

我正在嘗試使用GMT unix時間檢索用戶時區的已轉換「小時」整數。我的代碼在某些時候是有效的,但是例如,它是東海岸的晚上9點,並且每小時的時間爲0。誰能幫忙?從unix時間獲取當前時區的小時

long l = Long.parseLong(oslist.get(position).get("hour")); 

       Calendar calendar = Calendar.getInstance(); 
       calendar.setTimeInMillis(l); 
       calendar.setTimeInMillis(l * 1000); 
       calendar.setTimeZone(TimeZone.getDefault()); 

       int hour = calendar.get(Calendar.HOUR); 
       Log.v("TIME:", ""+hour); 

回答

-1

試試這個:

long l = Long.parseLong(oslist.get(position).get("hour")); 

    Calendar calendar = Calendar.getInstance(); 
    calendar.setTimeInMillis(l); 
    calendar.setTimeInMillis(l * 1000); 
    Date date = calendar.getTime(); //current date and time in UTC 
    SimpleDateFormat df = new SimpleDateFormat("HH"); //HH = 0-23 hours 
    df.setTimeZone(TimeZone.getDefault()); //format in given timezone 

    String hourStringValue = df.format(date); 
    int hourIntValue = Integer.parseInt(hourStringValue); 
+0

格式化爲字符串,然後解析是一種可行的方法來解決這個問題。 '日曆'很好。 –

+0

我不知道日曆默認情況下將時間轉換爲當前時區。感謝您的建議 –

-1

另外,如果你需要的時區本身,看Class SimpleDateFormat。特別是zZ格式。

+0

如果目的不是獲取字符串表示,則不需要使用'SimpleDateFormat'。 (OP的問題中沒有任何內容表明他們*想要轉換爲字符串。) –

2

您不需要設置時區 - 默認情況下,它是默認情況下的默認設置。並調用setTimeInMillis兩次是毫無意義的。所以剛:

Calendar calendar = calendar.getInstance(); 
calendar.setTimeInMillis(unixTimestamp * 1000L); 
int hour = calendar.get(Calendar.HOUR); 

...應該是絕對的罰款。如果不是,那麼通過其他答案建議的字符串表示方式不會起作用。

如果在東海岸晚上9點時給出0,這表明默認時區並不代表東海岸。我建議你先診斷一下:

System.out.println(TimeZone.getDefault().getID()); 
// Just in case the ID is misleading, what's the standard offset for this zone? 
System.out.println(TimeZone.getDefault().getRawOffset());