简体   繁体   English

Joda-Time Period似乎无法正确计算天数

[英]Joda-time Period doesn't seem to calculate days correctly

I am seeing some strange behavior around the Joda-time Period class -- specifically the days processing. 我在Joda-time Period类中看到一些奇怪的行为-特别是几天的处理。 In the following example code, I am specifying a period of 26 hours as milliseconds. 在下面的示例代码中,我指定26小时为毫秒。

// 26 hour duration
long durationMillis = 26 * 3600 * 1000;
Period period = new Period(durationMillis, PeriodType.dayTime());
// this fails because days == 0
assertEquals(1, period.getDays());
// this would fail because hours == 26
assertEquals(2, period.getHours());

I was expecting that Period would see that 26 hours is 1 day and 2 hours but it doesn't seem to be recognizing that a day == 24 hours. 我原以为Period会看到26个小时是1天2个小时,但似乎并没有意识到一天== 24个小时。

Any idea what am I doing wrong? 知道我在做什么错吗?

Turns out that Joda-time is wicket smaaart. 原来,乔达时代是检票口smaaart。 I guess that it can't know the number of hours in a day because of daylight savings time and other timezone issues. 我想由于夏时制和其他时区问题,它无法得知一天中的小时数。 There might be 23 or 25 hours in any particular day for example. 例如,在任何一天中可能有23或25个小时。

To force it to a 24 hours/day, you need to specific a Chronology that is consistent about hours per day. 要将其强制设置为每天24小时,您需要指定与每天的小时数保持一致的Chronology

long durationMillis = 26 * 3600 * 1000;
Period period = new Period(durationMillis, PeriodType.dayTime(),
    ISOChronology.getInstanceUTC());
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is needed to have 1 day == 24 hours
// this works!
assertEquals(1, period.getDays());
// this works!
assertEquals(2, period.getHours());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM