Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java Date Calculations

I would like to do simple date calculations in Java. For example, compute the difference in days between to dates (having a 0 time component). Of course you could do a simple substraction of milliseconds, divided by the number of milliseconds per day, which works fine - until daylight saving times enter the scene. I am conscious that different interpretations of the "difference in days" are possible, in particuliar, whether one should take into account the time component or not. Let us assume we have a 0 time component for simplicity.

This kind of calculation seems to be a very common need, and I would find it nice to have a discussion on different approaches to the question.

like image 486
mikemax Avatar asked Mar 13 '09 16:03

mikemax


People also ask

How do you calculate the difference between two dates in Java?

getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates. It returns the years, days, hours, minutes, and seconds between the two specifies dates.

How do you sum dates in Java?

long sum = d1. getTime() + d2. getTime(); Date sumDate = new Date(sum);

Which string method is used to calculate date and time?

String dateStart = "11/03/14 09:29:58"; String dateStop = "11/03/14 09:33:43"; // Custom date format SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.


1 Answers

I would have a look at the Joda date/time library, and in particular the ReadableInterval class.

Joda makes life a lot easier when manipulating dates/times in Java, and I believe it's the foundation of the new Java JSR 310 wrt. dates/times. i.e. it (or something very similar) will be present in a future version of Java.

like image 158
Brian Agnew Avatar answered Oct 19 '22 11:10

Brian Agnew