在开发的时候,因为本机时间有时不准确,而往往会有需要取精准的网络时间的情况,该方法可以用来获取网络时间
public static Date getNetTime(){
String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
try {
URL url = new URL(webUrl);
URLConnection uc = url.openConnection();
uc.setReadTimeout(5000);
uc.setConnectTimeout(5000);
uc.connect();
long correctTime = uc.getDate();
Date date = new Date(correctTime);
return date;
} catch (Exception e) {
return new Date();
}
}
webUrl这里用的是国家授时中心,也可以换成APP端调用的服务器地址,以获取服务器时间。这里设置了超时时长为5秒,若获取网络时间在5秒内无法获取,则返回本机时间。
将该方法单独封装为一个工具类,在子线程中进行调用即可。