org.joda.time.Period是否尊重闰年? [英] Does org.joda.time.Period respect leap years?

查看:540
本文介绍了org.joda.time.Period是否尊重闰年?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些单元测试,并发生在以下情况:



2015(不是闰年)

  LocalDate endDate = LocalDate.parse(01/03/2015,new DateTimeFormatterFactory(dd / MM / yyyy)createDateTimeFormatter()); 
LocalDate startDate = LocalDate.parse(25/02/2015,new DateTimeFormatterFactory(dd / MM / yyyy)。createDateTimeFormatter());

org.joda.time.Period.fieldDifference(startDate,endDate).getDays(); //是-24

2016(闰年)



pre> LocalDate endDate = LocalDate.parse(01/03/2016,新的DateTimeFormatterFactory(dd / MM / yyyy)createDateTimeFormatter());
LocalDate startDate = LocalDate.parse(25/02/2016,新的DateTimeFormatterFactory(dd / MM / yyyy)。createDateTimeFormatter());

org.joda.time.Period.fieldDifference(startDate,endDate).getDays(); // is ALSO -24

我希望这些值至少是不同的。



任何想法?

解决方案

fieldDifference


通过提取的字段差异计算差异
一个字段一次,而不是包装到其他字段。
因此2005-06-09 / 2007-04-12将产生P1Y-2M3D。


01/03/2016和25/02/2016之间的em> 是 1 - 25 = -24 。这不是说两天之间的天数。 -24 不会在任何一年的这两个日期之间的天数。



要找到两个日期之间的天数,您可以使用

  org.joda.time.Days.daysBetween(startDate,endDate).getDays ()

如果跨越2月底,2015年将从2016年起返回不同的数字。


I am doing some unit testing and have happened across this:

2015 (Not a Leap Year)

LocalDate endDate = LocalDate.parse("01/03/2015", new DateTimeFormatterFactory("dd/MM/yyyy").createDateTimeFormatter());
LocalDate startDate = LocalDate.parse("25/02/2015", new DateTimeFormatterFactory("dd/MM/yyyy").createDateTimeFormatter());

org.joda.time.Period.fieldDifference(startDate, endDate).getDays(); // is -24

2016 (Leap Year)

LocalDate endDate = LocalDate.parse("01/03/2016", new DateTimeFormatterFactory("dd/MM/yyyy").createDateTimeFormatter());
LocalDate startDate = LocalDate.parse("25/02/2016", new DateTimeFormatterFactory("dd/MM/yyyy").createDateTimeFormatter());

org.joda.time.Period.fieldDifference(startDate, endDate).getDays(); // is ALSO -24

I would expect these values to be at least different.

Any ideas?

解决方案

The doc for fieldDifference says

Calculation by field difference works by extracting the difference one field at a time and not wrapping into other fields. Thus 2005-06-09/2007-04-12 will yield P1Y-2M3D.

The difference in the day field between "01/03/2016" and "25/02/2016" is 1 - 25 = -24. It is not saying that is the number of days between the two dates. -24 would not make sense as the number of days between those two dates in any year.

To find the number of days between two dates, you could use

org.joda.time.Days.daysBetween(startDate, endDate).getDays()

which will indeed return a different number in 2015 from 2016 if it crosses the end of February.

这篇关于org.joda.time.Period是否尊重闰年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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