Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you subtract Dates in Java? [duplicate]

Tags:

java

datetime

My heart is bleeding internally after having to go so deep to subtract two dates to calculate the span in number of days:

    GregorianCalendar c1 = new GregorianCalendar();     GregorianCalendar c2 = new GregorianCalendar();     c1.set(2000, 1, 1);     c2.set(2010,1, 1);     long span = c2.getTimeInMillis() - c1.getTimeInMillis();     GregorianCalendar c3 = new GregorianCalendar();     c3.setTimeInMillis(span);     long numberOfMSInADay = 1000*60*60*24;     System.out.println(c3.getTimeInMillis() / numberOfMSInADay); //3653 

where it's only 2 lines of code in .NET, or any modern language you name.

Is this atrocious of java? Or is there a hidden method I should know?

Instead of using GregorianCalendar, is it okay to use Date class in util? If so, should I watch out for subtle things like the year 1970?

Thanks

like image 803
Haoest Avatar asked Aug 19 '10 21:08

Haoest


People also ask

Can we subtract date in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31. This instance is immutable and unaffected by this method call.

How do you add or subtract dates in Java?

DATE field can be used to add or subtract dates in Java. Positive value passed into add() method will add days into date while negative values will subtract days from date in Java. Similarly Calendar. MONTH can be used to add and subtract months from date in Java.


2 Answers

It's indeed one of the biggest epic failures in the standard Java API. Have a bit of patience, then you'll get your solution in flavor of the new Date and Time API specified by JSR 310 / ThreeTen which is (most likely) going to be included in the upcoming Java 8.

Until then, you can get away with JodaTime.

DateTime dt1 = new DateTime(2000, 1, 1, 0, 0, 0, 0); DateTime dt2 = new DateTime(2010, 1, 1, 0, 0, 0, 0); int days = Days.daysBetween(dt1, dt2).getDays(); 

Its creator, Stephen Colebourne, is by the way the guy behind JSR 310, so it'll look much similar.

like image 54
BalusC Avatar answered Oct 17 '22 19:10

BalusC


You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");  long d1=formater.parse("2001-1-1").getTime(); long d2=formater.parse("2001-1-2").getTime();  System.out.println(Math.abs((d1-d2)/(1000*60*60*24))); 
like image 40
daniel.deng Avatar answered Oct 17 '22 20:10

daniel.deng