How to calculate the time interval between Java date and Mysql date type?
天蓬老师
天蓬老师 2017-06-20 10:05:43
0
1
875

There is a field in the data table that stores the date type of MySQL. Every time it is read out, it is necessary to calculate the number of days between it and the current time. I am relatively clear about obtaining the current time, but how to convert the date read out from Mysql? I don’t quite understand the data conversion format and then calculating the time interval. The following is the code I wrote based on my own understanding. Please check if it is correct. info.get(15) is the date data read from the database

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);
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
学习ing

The easiest way:

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

In addition, if you encounter time zone problems, you may have a headache. The most complete solution is to save all dates in the database as BIGINTtype, and use Date.getTime()(UNIX timestamp in milliseconds ) value is stored in.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template