从unix时间获取当前时区的小时

问题描述 投票:0回答:4

我正在尝试使用 GMT unix 时间检索用户时区的转换后的“小时”整数。我的代码有时会起作用,但例如,当时是东海岸晚上 9:00,并且该小时的时间为 0。有人可以帮忙吗?

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);
java android unix calendar timezone
4个回答
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());

0
投票

java.time

java.util
日期时间 API 及其相应的解析/格式化类型
SimpleDateFormat
已过时且容易出错。 2014 年 3 月,现代日期时间 API 取代了该 API。从那时起,强烈建议切换到现代日期时间 API
java.time

使用

java.time
API 的解决方案:

您可以使用

Instant#ofEpochSecond
来获取与您给定的 Unix 时间戳对应的
Instant
。接下来,将
Instant
转换为所需时区的
ZonedDateTime
,然后您可以从中获取单独的时间单位(例如小时)。
ZonedDateTime

输出:

// e.g. a Unix timestamp representing 9:00pm on 10-Sep-2023 in New York long epochSeconds = 1694394000L; Instant instant = Instant.ofEpochSecond(epochSeconds); ZonedDateTime zdt = instant.atZone(ZoneId.of("America/New_York")); System.out.println(zdt); System.out.println(zdt.getHour());

在线演示

Trail:日期时间了解现代日期时间 API


-1
投票
Class SimpleDateFormat

。特别是 2023-09-10T21:00-04:00[America/New_York] 21

z
格式。
    


-2
投票

Z

© www.soinside.com 2019 - 2024. All rights reserved.