Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I learn how many days passed from a specific date?

Tags:

java

How can I learn how many days passed from a spesific date? Which package i need to use and how?

like image 906
CapedAvenger Avatar asked May 31 '11 10:05

CapedAvenger


People also ask

How do you make Excel automatically count days from a specific date?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.


2 Answers

Just for the protocol - i love java.util.concurrent.TimeUnit for that things.

Date d1 = ...
Date d2 = ...
long dif = d1.getTime() - d2.getTime();
long days = TimeUnit.MILLISECONDS.toDays(dif);

So basically exactly what the answer from morja is, but using TimeUnit for calculating time things around. Having values like 24, 60 etc. directly in your code violates Java Code Conventions (which only allow -1, 0 and 1 directly in code) and is harder to read.

like image 194
Fabian Barney Avatar answered Oct 17 '22 03:10

Fabian Barney


EDIT My previous answer was only valid within a year.

You can use the milliseconds difference like this:

Date date1 = // some date
Date date2 = // some other date
long difference = date2.getTime() - date1.getTime();
long differenceDays = difference / (1000 * 60 * 60 * 24);

Basically the same as timbooo answered, just a shorter way.

like image 4
morja Avatar answered Oct 17 '22 05:10

morja