【Java】从网络获取北京时间

<pre code_snippet_id="432698" snippet_file_name="blog_20140722_1_3232278" name="code" class="java"><pre name="code" class="java">public static void main(String[] args) throws Exception {
       TimeZone.setDefault(TimeZone.getTimeZone("GMT+8")); // 时区设置
       URL url=new URL("http://www.bjtime.cn");//取得资源对象
       URLConnection uc=url.openConnection();//生成连接对象
       uc.connect(); //发出连接
       long ld=uc.getDate(); //取得网站日期时间(时间戳)
       Date date=new Date(ld); //转换为标准时间对象
       //分别取得时间中的小时,分钟和秒,并输出
       System.out.print(date.getHours()+"时"+date.getMinutes()+"分"+date.getSeconds()+"秒");
 }


 
 

                
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
您可以使用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地址和解析方式。注意,这种方法获取的是服务器的时间,而不是本地时间
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值