Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract two joda datetimes? [duplicate]

I know this isn't "the way it's supposed to work", but still: If you have two DateTime objects, what's a good way to subtract them? Convert them to Date objects?

DateTime start = new DateTime(); System.out.println(start + " - doing some stuff");  // do stuff  DateTime end = new DateTime(); Period diff = // end - start ??? System.out.println(end + " - doing some stuff took diff seconds"); 
like image 719
ripper234 Avatar asked Apr 04 '13 15:04

ripper234


People also ask

Can we subtract two dates 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 subtract two date strings in Java?

Date diff = new Date(d2. getTime() - d1. getTime()); Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch.

What is Joda-Time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.


2 Answers

Period has a constructor that takes two ReadableInstant instances:

Period diff = new Period(start, end); 

(ReadableInstant is an interface implemented by DateTime, as well as other classes.)

like image 123
millimoose Avatar answered Sep 18 '22 21:09

millimoose


From your example you seem to want the difference in seconds so this should help :

Seconds diff = Seconds.secondsBetween(start, end); 
like image 25
bowmore Avatar answered Sep 20 '22 21:09

bowmore