获取网络时间,有些网站有偏差,提供几个比较靠谱的网站:
/** * 读取网络时间 * */ public class NetworkTime { public static void main(String[] args) { String webUrl1 = "http://www.bjtime.cn";//bjTime String webUrl2 = "http://www.baidu.com";//百度 String webUrl3 = "http://www.taobao.com";//淘宝 String webUrl4 = "http://www.ntsc.ac.cn";//中国科学院国家授时中心 String webUrl5 = "http://www.360.cn";//360 String webUrl6 = "http://www.beijing-time.org";//beijing-time System.out.println(" [bjtime] : "+getWebsiteDatetime(webUrl1)); System.out.println(" [百度]: "+getWebsiteDatetime(webUrl2)); System.out.println(" [淘宝]: "+getWebsiteDatetime(webUrl3)); System.out.println(" [中国科学院国家授时中心]: "+getWebsiteDatetime(webUrl4)); System.out.println(" [360安全卫士]: "+getWebsiteDatetime(webUrl5)); System.out.println( " [beijing-time]: "+getWebsiteDatetime(webUrl6)); } /** * 获取指定网站的日期时间 * * @param webUrl * @return */ public static long getWebsiteDatetime(String url){ try { URL url = new URL(webUrl);// 取得资源对象 URLConnection uc = url.openConnection();// 生成连接对象 uc.connect();// 发出连接 long ld = uc.getDate();// 读取网站日期时间 return ld; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; } /** * 调用此方法输入所要转换的时间戳输入例如(1402733340)输出("2014年06月14日16时09分00秒") * * @param time * @return */ public static String times(long time) {//转换时间戳 SimpleDateFormat sdr = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"); String times = sdr.format(new Date(time)); return times; } }
经过测试得到结果:
"http://www.bjtime.cn";//bjTime 结果分析:这个网站的时间获得偏差在1分半左右
"http://www.baidu.com";//百度 结果分析:比较准
"http://www.taobao.com";//淘宝 结果分析:比较准
"http://www.360.cn";//360 结果分析:比较准
"http://www.ntsc.ac.cn";//中国科学院国家授时中心 结果分析:与网站显示的时间偏差10秒内
"http://www.beijing-time.org";//beijing-time 结果分析:WiFi和宽带访问比较准,但4G访问偏差较大,偏差值很不稳定
这个结果是自测的,仅供参考
