Java (Joda): Seconds from midnight of LocalDateTime

自闭症网瘾萝莉.ら 提交于 2019-12-12 02:52:40

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/19622332/java-joda-seconds-from-midnight-of-localdatetime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!