有什么方法可以将 JodaTime 周期转换为十进制小时数吗?
我有一个从两个 DateTime 时刻创建的 JodaTime 周期。有没有一种好方法将该周期转换为十进制小时数?
例如,我有一个从 2010 年 1 月 1 日下午 1 点到下午 1:30 的经期。我怎样才能将该经期设为 1.5 小时。
过去,我使用秒和 BigDecimal 进行手动转换,如下所示:
int seconds = myPeriod.toStandardSeconds().getSeconds();
BigDecimal d = new BigDecimal((double) seconds / 3600);
// Round to two decimals
BigDecimal correctResult = d.setScale(2, RoundingMode.HALF_DOWN);
这种感觉就像黑客,更不用说当我开始将句点添加在一起时的尴尬。看来应该有更好的办法。
有什么想法吗? 谢谢
I have a JodaTime Period that I've created from two DateTime instants. Is there a good way to convert that Period into a decimal number of hours?
For instance, I have a Period that goes from 1pm to 1:30pm on Jan 1, 2010. How can I get that Period as 1.5 hours.
In the past I've manually converted using seconds and BigDecimals such as this:
int seconds = myPeriod.toStandardSeconds().getSeconds();
BigDecimal d = new BigDecimal((double) seconds / 3600);
// Round to two decimals
BigDecimal correctResult = d.setScale(2, RoundingMode.HALF_DOWN);
This kind of feels like a hack, not to mention awkward when I start adding Periods together. It seems like there should be a better way.
Any ideas?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有两个 DateTimes,我希望您在它们之间有一个
Duration
而不是Period
...但除此之外和 Mike 的评论之外,看起来正确:请注意,您可以使用
Duration.getMillis()
来避免使用toStandardSeconds().getSeconds()
:If you've got two DateTimes, I'd expect you to have a
Duration
between them rather than aPeriod
... but other than that and Mike's comments, that looks correct:Note that you can avoid the
toStandardSeconds().getSeconds()
usingDuration.getMillis()
instead:有点旧,但我最近在看这个,您可以使用
DateTimeFormatterBuilder
来执行此操作。它有一系列名为appendFraction...
的方法,它将附加小时、分钟、秒等的一小部分。这并不完全是您所要求的,因为您使用的是
Period< /code> 但您可以通过在午夜创建一个新的
DateTime
来解决此问题。该格式化程序应该解析您的日期时间:
然后您可以执行类似的操作来转换您的周期:
A bit old but I was looking at this recently and you can use the
DateTimeFormatterBuilder
to do this. It has a series of methods calledappendFraction...
which will append a fraction of an hour, minute, second etc.This is not exactly what you were asking as you were using a
Period
but you can work around this by making a newDateTime
at midnight.This formatter should parse your DateTime:
You could then do something like this to convert your period:
使用 Jon Skeet 示例,除法 BigDecimal
divide(MILLIS_PER_HOUR)
会出现非终止十进制扩展异常
,用于修复错误更改代码这:Using the Jon Skeet example, you have a
Non-terminating decimal expansion Exception
from divide BigDecimaldivide(MILLIS_PER_HOUR)
, for fix error alter code for this: