在網上看到的最常見的方式有:
public static void main(String[] args) throws Exception {
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()+"秒");
}
來源:http://blog.sina.com.cn/s/blog_79d3696301015xo9.html
原理:通過訪問http://www.bjtime.cn網站來獲取
這里還為大家提供另外一種方式:通過網絡或者GPS的方式。
代碼:
LocationManager locMan = (LocationManager) this.getSystemService(MainActivity.LOCATION_SERVICE);
//獲取最近一次知道的時間
long networkTS = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime();
或者實時的獲取時間:
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); //獲取當前時間
當我們使用requestLocationUpdates時,我們需要實現LocationListener接口。
在LocationListen的回調onLocationChanged當中獲取時間
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
long time = location.getTime();
Date date = new Date(time);
System.out.println(time + " NETWORK_PROVIDER " + date);
// System.out.println(STANDARD_TIME + " ");
}
@hnrainll