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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Java中的`java.net.URL`和`java.HttpURLConnection`类来获取网络时间。以下是一个示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class NetworkTimeExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://www.baidu.com"); // 打开URL连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方式为GET connection.setRequestMethod("GET"); // 获取响应码 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 读取响应内容 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 解析响应内容提取时间信息 String timeStr = response.toString(); // 假设响应内容包含时间信息 // 进行时间解析和处理 System.out.println("网络时间:" + timeStr); } else { System.out.println("获取网络时间失败,响应码:" + responseCode); } // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这个例子通过发送一个GET请求到百度网址(http://www.baidu.com),然后获取到响应内容并解析出时间信息。您可以根据自己的需求修改URL地址和解析方式。注意,这种方法获取的是服务器的时间,而不是本地时间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值