简体   繁体   中英

How to calculate difference in days between the one from database and current date using java

I retrieve the date from database (using mysql)

java.sql.Date dbSqlDateLastRecord = result.getDate("date");

java.util.Date LastRecord = new java.util.Date(dbSqlDateLastRecord.getTime());  

and also get a present date

LocalDate today = LocalDate.now(); 

However I didn't find how to calculate the difference in days between those two. How it can be done? By 'difference' I mean that if I have the following two: 2018-05-25" and "2018-05-24" I will get 1.

You mean :

java.sql.Date dbSqlDateLastRecord = result.getDate("date");

//Convert java.sql.Date to LocaDate
LocalDate dateDB = dbSqlDateLastRecord.toLocalDate();

LocalDate dateSS = LocalDate.now();

Then you can Get difference between them :

import java.time.Duration;
...
long days = Duration.between(dateDB.atStartOfDay(), dateSS.atStartOfDay()).toDays();

Or :

import java.time.temporal.ChronoUnit;
...
long days = ChronoUnit.DAYS.between(dateDB, dateSS);

Don't use java.sql.Date . Don't use java.util.Date . Both classes are long outdated. Also don't use any conversions. Get a LocalDate from the database:

    LocalDate dateDB = result.getObject("date", LocalDate.class);

This requires at least Java 8 and at lease JDBC 4.2. My guess is you're long there. Then proceed as in YCF_L' answer , for example:

    long days = ChronoUnit.DAYS.between(dateDB, dateSS);

Also just store a LocalDate back into your database, for example

    yourPreparedStatement.setObject(4, LocalDate.now(yourZoneId));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM