Android 从 ntp 服务器获取 UTC 时间

Android Get UTC time from ntp server

我正在尝试获取服务器的当前 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() 总是 returns 特定时区的输出。您的 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));