import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* 获取网络时间
*
*/
public class NetworkTimeUtil {
/**
* 获取网络时间
*
* @return
* @throws Exception
*/
public static Date getNetworkTime() throws Exception {
URL url = new URL("http://bjtime.cn");// 取得资源对象
URLConnection uc = url.openConnection();// 生成连接对象
uc.connect(); // 发出连接
long ld = uc.getDate(); // 取得网站日期时间
Date date = new Date(ld); // 转换为标准时间对象
return date;
}
// 测试
public static void main(String[] args) throws Exception {
NetworkTimeUtil ntu = new NetworkTimeUtil();
Date date = ntu.getNetworkTime();
// 分别取得时间中的小时,分钟和秒,并输出
System.out.println("date:" + date);
System.out.println(new SimpleDateFormat("yyyy-MM-dd hh-mm-ss")
.format(date));
}
}