2015-06-25 154 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());