如何计算Java date与Mysql的date类型的时间间隔?
问题描述
数据表里有个字段存放的是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时间戳)的值存进去。
相关文章:
1. angular.js - 关于指令link 中的创建变量问题2. java - 当系统出现线程死锁时怎么处理?3. angular.js - angularJS最简单方法实现点击checkbox,button变亮4. angular.js - form 表单,点击提交按钮 判断ng-checked 已选中5. angular.js - 有人看过Angular即学即用这本书吗6. 记不住代码有什么好的方法吗?7. vue计算属性怎么样与for结合使用8. javascript - H5下拉能更换页面么 怎么实现 在左右滑的页面中9. ubuntu apt-get install update 无法更新10. vue.js - vue上传代码到git