话不多说,直接贴代码
第一步 引用第三方包:
compile 'commons-net:commons-net:3.6'
第二步 使用该包
public class NtpUntil { public static Long getNtpTime() { try { NTPUDPClient timeClient = new NTPUDPClient(); String timeServerUrl = "118.24.4.66"; InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl); TimeInfo timeInfo = timeClient.getTime(timeServerAddress); TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = timeStamp.getDate(); System.out.println(dateFormat.format(date)); return date.getTime(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0L; }
第三步 结束。
最后 android同步时间很少,java同步时间就很多了,有时候android上找不到资源,不如换关键词java。
这个同步时间,别的android博客说的很复杂,但是没什么用。
java博客就很简单,而且很实用。