您的位置:首页技术文章
文章详情页

如何计算Java date与Mysql的date类型的时间间隔?

【字号: 日期:2022-06-11 11:09:07浏览:72作者:猪猪

问题描述

数据表里有个字段存放的是MySQL的date类型,每次读出的时候要计算和当前时间的间隔是多少天,获取当前时间我比较清楚,但是如何将Mysql中读出的date数据转换格式然后计算时间间隔就不太懂了,下面是我按自己的理解写的代码,请大家看看是不是对的。info.get(15)是从数据库中读出的date数据

SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd');Calendar cal = Calendar.getInstance();String Time1 = sdf.format(new Date());String Time2 = info.get(15).toString;try { cal.setTime(sdf.parse(Time1)); } catch (ParseException e) {e.printStackTrace(); } long oldTime = cal.getTimeInMillis(); try { cal.setTime(sdf.parse(Time2)); } catch (ParseException e) {e.printStackTrace(); }long now1 = cal.getTimeInMillis();long days = (now1 - old) / (1000*3600*24);

问题解答

回答1:

最简单的做法:

(System.currentTimeMillis() - info.getDate().getTime()) / 86400000

另外,如果碰到时区问题,可能会比较头疼,最彻底的解决办法是数据库里所有的日期都存为BIGINT类型,把Date.getTime()(以毫秒为单位的UNIX时间戳)的值存进去。

相关文章: