【发布时间】:2019-07-04 18:00:04
【问题描述】:
我无法获得当前的印度时间。
我想获得印度的当前时间,我在 5 分钟后更新了我的系统时钟,然后是当前时间,所以我的系统时钟比实际印度时间早 5 分钟,但我想获得印度的标准时间。
current time is 11:05:06 and machine time is 11:10:06
public class TestDate {
public static void main(String[] args) {
SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
Date date = new Date();
sd.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sd.format(date));
}
}
output : 2019.02.12 AD at 11:10:06 IST
expected : 2019.02.12 AD at 11:05:06 IST
但我得到了错误的输出,所以请建议
【问题讨论】:
-
我建议你不要使用
SimpleDateFormat、TimeZone和Date。这些类设计不佳且过时已久,尤其是第一个类是出了名的麻烦。而是使用ZonedDateTime、ZoneId和DateTimeFormatter,均来自java.time, the modern Java date and time API。 -
您所在时区的系统时间是否正确?如果没有,您应该同步它。如果你不能,那么你需要在某个地方使用 web api 来获取正确的时间。
-
@TiiJ7 是的,这才是真正的“问题”,现在我明白了
-
你总是会得到运行命令的机器的时间,句号。获得其他时间的唯一方法是调用时间服务,例如 NTP 服务器,然后向它请求。