首页 >社区问答列表 >如何计算Java date与Mysql的date类型的时间间隔?

如何计算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);

  • 学习ing
  • 学习ing    2017-06-20 10:07:431楼

    最简单的做法:

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

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

    +0添加回复

  • 回复