獲取網絡時間(國家標準時間-北京時間爲準)

獲取網絡時間,有些網站有偏差,提供幾個比較靠譜的網站:

/**
 * 讀取網絡時間
 *
 */
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訪問偏差較大,偏差值很不穩定


這個結果是自測的,僅供參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章