Java(Joda):从LocalDateTime午夜开始经过的秒数 [英] Java (Joda): Seconds from midnight of 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屋!