Reputation: 26
I have two timestamp values. like
Timestamp date1;
Timestamp date2;
Now I want to find no. of days between these two timeStamps like in java
int no_of_days = difference(date2 - date1)
the above codes are just for clarification of the question. just ignore the coding mistakes.
Upvotes: 0
Views: 1182
Reputation: 44071
Other answers given here so far only handle a day unit as fixed amount of 24 hours by using the class java.time.Duration
. If you consider your timestamps in the context of daylight saving switching time zones then this is probably not what you want.
During the change from winter to summer time, a calendar day can last only 23 hours (or even 23:30 in some rare cases). And in autumn when switching back to winter time, the calendar days can be more than 24 hours long. So you also need a time zone to handle this situation in order to calculate durations in the correct way.
Suggested solution if your timestamps have been stored in the database coming from instants:
ZonedDateTime zdt1 = date1.toInstant().atZone(ZoneId.systemDefault());
ZonedDateTime zdt2 = date2.toInstant().atZone(ZoneId.systemDefault());
long days = java.time.temporal.ChronoUnit.DAYS.between(zdt1, zdt2);
Of course, you are free to specify any other zone than the system time zone. The result can vary depending on the chosen zone.
Suggested solution if your timestamps have been stored coming from LocalDateTime
without any zone context:
LocalDateTime ldt1 = date1.toLocalDateTime();
LocalDateTime ldt2 = date2.toLocalDateTime();
long days = java.time.temporal.ChronoUnit.DAYS.between(ldt1, ldt2);
Here I still prefer the enum ChronoUnit.DAYS
because the type java.time.Duration
internally stores seconds and nanoseconds only and is hence rather designed for machine-like timestamps. And another remark: The second solution implicitly uses your system time zone for the conversion from java.sql.Timestamp
to LocalDateTime
. This is only correct if you also have stored your timestamps that way.
By the way, with a JDBC-4.2-compliant driver, you could also retrieve your java.time
-type directly, see also a related post here on SO.
Upvotes: 1
Reputation: 21124
If you are using Java8, it will be much easier. Here's a one way of doing it.
Duration.between(date1.toLocalDateTime(), date2.toLocalDateTime()).toDays();
Upvotes: 1
Reputation: 3947
You can use Duration
for this (it works for java 8) :
Duration between = Duration.between(date1.toInstant(), date2.toInstant());
int no_of_days = between.get(ChronoUnit.DAYS);
Upvotes: 1