获取北京时间
public static Date getBeiJingTime() throws Exception {
Locale locale = Locale.CHINA; //这是获得本bai地中国时du区
String pattern = “yyyy-MM-dd kk:mm:ss”;//这是日期格式
SimpleDateFormat df = new SimpleDateFormat(pattern, locale);//设定日期格式
Date date = new java.util.Date();
//URL url=new URL(“http://www.bjtime.cn”);//取得资源对象(这个网址经常失败)
URL url = new URL(“http://www.gov.cn/”);//取得资源对象 国务院网站时间
URLConnection uc = url.openConnection();//生成连接对象
uc.connect(); //发出连接
long ld = uc.getDate(); //取得网站日期时间
date = new Date(ld); //转换为标准时间对象
return date;
}
比较两个时间相差得天数、小时、分钟、秒
public static String getDistanceTime(Date starttime, Date endtime){
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
long time1 = starttime.getTime();
long time2 = endtime.getTime();
long diff ;
if(time1<time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
day = diff / (24 * 60 * 60 * 1000);
hour = (diff / (60 * 60 * 1000) - day * 24);
min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
return day + "天" + hour + "小时" + min + "分" + sec + "秒";
}
调用方式:类名.方法名(参数)