I know this is probably a really stupid question, however I was wondering whether there is a way to minus a local date time from another, or if not, to cast localDateTime to just Date time and then subtract from there?
I need to be able to work out the date time difference, between the start of record foo and the start of record bar (which is also the end of Foo)
I am rather new to java, and for simplicity's sake, I want to be able to keep it in roughly the same layout, rather than having to convert from seconds etc.
If adding and subtracting LocalDateTime is not an option, I know that once I am in dateTime I am able to subtract them using:
Period diff = new Period(start, end);
Due to the purpose of the data, I need to keep both the date and the time in order for this to work, and as mentioned before, I wish to keep it fairly simple so theres no need to convert between seconds back to the date.
My issue is really just getting it in an acceptable format, as I say, I am rather new to java and object orientation as a whole, so please don't ridicule me for this, seemingly simple, question.
Thanks,
Jonny
An immutable copy of a LocalDateTime where the required duration is subtracted from it can be obtained using the minus() method in the LocalDateTime class in Java. This method requires two parameters i.e. the duration to be subtracted and the TemporalUnit of the duration.
Here's a way to calculate the difference although not necessarily the fastest: LocalDateTime fromDateTime = LocalDateTime. of(1984, 12, 16, 7, 45, 55); LocalDateTime toDateTime = LocalDateTime. of(2014, 9, 10, 6, 40, 45); LocalDateTime tempDateTime = LocalDateTime.
minus(long amountTosubtract, TemporalUnit unit)minus() method of a LocalDate class used to Returns a copy of this LocalDate with the specified amount of unit subtracted to LocalDate. If it is not possible to subtract the amount, because the unit is not supported or for some other reason, an exception is thrown.
parse(CharSequence text, DateTimeFormatter formatter) Return value: This method returns LocalTime which is the parsed local date-time. Exception: This method throws DateTimeParseException if the text cannot be parsed.
Why do you not simply use directly LocalDateTime
as parameter type this way:
LocalDateTime start = new LocalDateTime(2016, 10, 4, 17, 45);
LocalDateTime end = LocalDateTime.now();
PeriodType ptype = PeriodType.yearMonthDayTime();
Period diff = new Period(start, end, ptype);
See also the API of Joda-Time. You don't need to cast to DateTime
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With