计算两个日期时间差实例代码
计算两个日期时间差实例代码:
public static void main(String[] args) throws ParseException{
??SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
??Date currentTime=new Date();
??//将截取到的时间字符串转化为时间格式的字符串
??Date beginTime=sdf.parse("2010-07-27 12:53:30");
??//默认为毫秒,除以1000是为了转换成秒
??long interval=(currentTime.getTime()-beginTime.getTime())/1000;//秒
??long day=interval/(24*3600);//天
??long hour=interval%(24*3600)/3600;//小时
??long minute=interval%3600/60;//分钟
??long second=interval%60;//秒
??System.out.println("两个时间相差:"+day+"天"+hour+"小时"+minute+"分"+second+"秒");
?}
可以把数据库的日期时间转换成毫秒数,然后计算间隔时间差,如果只想计算出两个时间相差几天可以:间隔秒数/60*60*24。
注意:数据库中或提供的日期时间格式一定要与SimpleDateFormat("yyyy-MM-dd HH:mm:ss")中的日期格式一致,不然会出错的。