Java(Joda):从LocalDateTime午夜开始经过的秒数 [英] Java (Joda): Seconds from midnight of LocalDateTime

查看:128
本文介绍了Java(Joda):从LocalDateTime午夜开始经过的秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用这个:

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());

它弄乱了时区(我少了1小时).

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.

我绝对需要使用LocalDateTime作为输入类型,请不要与其他类一起发布解决方案.

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;

(如果确实要使用DateTimeConstants.MILLIS_PER_SECOND-在这种情况下,我认为每秒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.

如果您确实希望将其作为期间,则可以使用LocalDateTime.withMillisOfDay(0)在同一天的午夜获取LocalDateTime,例如

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();

...但是我个人可能只使用getMillisOfDay.

... but personally I'd probably just use getMillisOfDay.

这篇关于Java(Joda):从LocalDateTime午夜开始经过的秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆