我正在尝试获取服务器的当前 UTC 时间,但它给了我时区时间 (UTC+6),有没有办法在不使用设备时间的情况下获得 UTC 时间?
我的代码:
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName("time1.google.com");
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getMessage().getOriginateTimeStamp().getTime();
long returnTime2 = timeInfo.getReturnTime();
Date current = new Date(returnTime);
Date current1 = new Date(returnTime2);
Log.i("actualtime", current.toString()); //it give me UTC+6
Log.i("actualtime",current1.toString()); //it give me UTC+6
谢谢!
最佳答案
Date.toString()
始终返回时区特定的输出。您的 returnTime
变量实际上可能是正确的纪元时间:如果您想打印出 UTC,请使用 SimpleDateFormat
来执行此操作。像这样:
SimpleDateFormat fmt = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ssZ");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + fmt.format(current));
关于Android从ntp服务器获取UTC时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43268613/