I could not find any hand method on java.util.Date
function in order to get number of days between 2 dates?
How should I get number of days?
CodePudding user response:
First, convert your legacy java.util.Date
objects to their modern replacements, java.time.Instant
. Call new methods added to the old classes.
Instant start = javaUtilDateStart.toInstant() ;
If by “number of days” you mean “number of 24-hour chunks of time”, without regard for calendar, use Duration
.
long days = Duration.between( start , end ).toDays() ;
If you meant calendar days, you need to specify the time zone by which you want to perceive dates.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
Apply that zone to Instant
to produce a ZonedDateTime
. Same moment, same point on the timeline, different wall-clock time and date.
ZonedDateTime startZdt = start.atZone( z ) ;
Calculate elapsed days using ChronoUnit
enum DAYS
.
long days = ChronoUnit.between( startZdt , endZdt ) ;