I tried to use this:
secondsFromMidnight = Seconds.secondsBetween(localDateTime.toLocalDate(),
localDateTime).getSeconds();
but it throws an exception (cf. below). I think this is a good approach, but I did not succeed in adapt it to my case yet. If I write this:
DateTime dateTimeFromMidnight = new DateMidnight(localDateTime.getChronology()).toDateTime();
Duration duration = new Duration(dateTimeFromMidnight, localDateTime.toDateTime());
it messes up with time zones (I get 1 hour less).
If your solution is also easily adaptable for hours, minutes and so on, that's a plus.
I need absolutely to use LocalDateTime as input type, please do not post solutions with other classes.
Exception in thread "main" java.lang.IllegalArgumentException: ReadablePartial objects must have the same set of fields
at org.joda.time.base.BaseSingleFieldPeriod.between(BaseSingleFieldPeriod.java:92)
at org.joda.time.Seconds.secondsBetween(Seconds.java:124)
If you want to know the time of day, in seconds since midnight, it would be easiest to just use getMillisOfDay()
:
int secondsOfDay = localDateTime.getMillisOfDay() / 1000;
(Use DateTimeConstants.MILLIS_PER_SECOND
if you really want to - in this case I think the knowledge of "1000 milliseconds per second" is easy enough.)
You can use the same approach for minutes and hours, of course.
If you really want it as a period, you could use LocalDateTime.withMillisOfDay(0)
to obtain a LocalDateTime
at midnight of the same day, e.g.
secondsFromMidnight = Seconds.secondsBetween(localDateTime.withMillisOfDay(0),
localDateTime)
.getSeconds();
... but personally I'd probably just use getMillisOfDay
.
See more on this question at Stackoverflow