java获取网络时间
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String webUrl = "http://www.baidu.com";// 百度
TimeZone.setDefault(TimeZone.getTimeZone("GMT+08:00")); // 时区设置(北京时间)
try {
URL url = new URL(webUrl);//取得资源对象
URLConnection conn = url.openConnection();//生成连接对象
conn.connect();//发出连接
long dateL = conn.getDate();//取得网站日期时间(时间戳)
Date date = new Date(dateL);//转换为标准时间对象
//分别取得时间中的小时,分钟和秒,并输出
System.out.print(date.getHours()+"时"+date.getMinutes()+"分"+date.getSeconds()+"秒");
} catch (MalformedURLException e) {//url书写异常,就是没有书写正确的url
e.printStackTrace();
} catch (IOException e) {//
e.printStackTrace();
}
}
}