Java 获取本地时间与网络时间

  为了防止用户通过修改本地时间做一些不符合业务逻辑的事,有时候我们有必要获取网络时间做一些关于时间的计算


//Calendar 获取本地时间
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(calendar.getTime())+" : By Calendar");
//Date 获取本地时间
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(date.getTime())+" : By Date");
//获取网络时间
String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
String webUrl_baidu = "http://www.baidu.com";// 百度
String webUrl_taobao = "http://www.taobao.com";// 淘宝
System.out.println(getWebsiteDatetime(webUrl4) + " [中国科学院国家授时中心]");
private static String getWebsiteDatetime(String webUrl){
    try {
        URL url = new URL(webUrl);// 取得资源对象
        URLConnection uc = url.openConnection();// 生成连接对象
        uc.connect();// 发出连接
        long ld = uc.getDate();// 读取网站日期时间
        Date date = new Date(ld);// 转换为标准时间对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间
        return sdf.format(date);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/zheng_xiao_xin/article/details/80811181