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

public class DateDemo {

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

String webUrl7 = "http://www.163.com/";// 网易

String webUrl8 = "https://www.tmall.com/";// 天猫

System.out.println(getNetworkTime(webUrl1) + " [bjtime]");

System.out.println(getNetworkTime(webUrl2) + " [百度]");

System.out.println(getNetworkTime(webUrl3) + " [淘宝]");

System.out.println(getNetworkTime(webUrl4) + " [中国科学院国家授时中心]");

System.out.println(getNetworkTime(webUrl5) + " [360安全卫士]");

System.out.println(getNetworkTime(webUrl6) + " [beijing-time]");

System.out.println(getNetworkTime(webUrl7) + " [网易]");

System.out.println(getNetworkTime(webUrl8) + " [天猫]"); }

public static String getNetworkTime(String webUrl) {

try {

URL url = new URL(webUrl);

URLConnection conn = url.openConnection();

conn.connect();

long dateL = conn.getDate();

Date date = new Date(dateL);

SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

return dateFormat.format(date);

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return ""; }}

您可以使用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、付费专栏及课程。

余额充值