在项目中我们经常需要获取当前的时间,时间又分系统时间和网络时间
1.获取系统时间
Calendar c = Calendar.getInstance();
//取得系统日期:
year = c.get(Calendar.YEAR)
month = c.grt(Calendar.MONTH)
day = c.get(Calendar.DAY_OF_MONTH)
//取得系统时间:
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE)
2.获取网络时间
private void getNetTime() {
URL url = null;//取得资源对象
try {
url = new URL("http://www.baidu.com");
//url = new URL("http://www.ntsc.ac.cn");//中国科学院国家授时中心
//url = new URL("http://www.bjtime.cn");
URLConnection uc = url.openConnection();//生成连接对象
uc.connect(); //发出连接
long ld = uc.getDate(); //取得网站日期时间
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(ld);
data = calendar.get(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
e.printStackTrace();
}
}