Posted By

pablazo on 09/29/06

Statistics

Viewed 324 times
Favorited by 0 user(s)

Diferencia entre fechas JAVA

/ Published in: Java  Copy this code and paste it in your HTML
1. // First convert the from and to Calender to long (milli seconds)
2. // MAKE SURE THE Hour, Seconds and Milli seconds are set to 0, if you
3. // already have you own Claender object otherwise the time will be
4. // used in the comparision, later on.
5. long from = new java.util.GregorianCalendar(2003, 1, 20).getTime().getTime();
6. long to = new java.util.GregorianCalendar(2003, 2, 5).getTime().getTime();
7.
8.
9. // Next subtract the from date from the to date (make sure the
10. // result is a double, this is needed in case of Winter and Summer
11. // Time (changing the clock one hour ahead or back) the result will
12. // then be not exactly rounded on days. If you use long, this slighty
13. // different result will be lost.
14. double difference = to - from;
15.
16.
17. // Next divide the difference by the number of milliseconds in a day
18. // (1000 * 60 * 60 * 24). Next round the result, this is needed of the
19. // Summer and Winter time. If the period is 5 days and the change from
20. // Winter to Summer time is in the period the result will be
21. // 5.041666666666667 instead of 5 because of the extra hour. The
22. // same will happen from Winter to Summer time, the result will be
23. // 4.958333333333333 instead of 5 because of the missing hour. The
24. // round method will round both to 5 and everything is OKE....
25. long days = Math.round((difference/(1000*60*60*24)));
26.
27.
28. // Now we can print the day difference... Try it, it also works with
29. // Feb 29...
30. System.out.println(days); Subscribe to comments