问题描述
我创建了一个使用jodatime的Utility方法来计算日期差并将其显示为3y 2m 4d.
I created a Utility method using jodatime to calculate date difference and display it such as 3y 2m 4d.
这是我的方法:
public static String dateBetween(Object start, Object end) {
Period period = new Period(new LocalDate(start), new LocalDate(end));
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears().appendSuffix("y ")
.appendMonths().appendSuffix("m ")
.appendDays().appendSuffix("d")
.toFormatter();
return formatter.print(period);
}
使用testng创建测试脚本,如下所示:
The test scripts are created using testng as follow:
@DataProvider(name = "dateBetweenData")
public static Object[][] dateBetweenData() {
return new Object[][] {
{ "01/08/2010", "02/07/2012", "1y 11m 1d" },
{ "01/08/2010", "03/07/2012", "1y 11m 2d" },
{ "01/08/2010", "11/07/2012", "1y 11m 10d" },
{ "01/08/2010", "21/07/2012", "1y 11m 20d" },
{ "01/08/2010", "31/07/2012", "1y 11m 30d" },
};
}
@Test(dataProvider="dateBetweenData")
public void dateBetween(String startDate, String endDate, String expected) throws ParseException {
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Assert.assertEquals(
DateUtil.dateBetween(format.parse(startDate), format.parse(endDate)),
expected);
}
我注意到我的某些测试失败:
I noticed that some of my tests are failed:
PASSED: dateBetween("01/08/2010", "02/07/2012", "1y 11m 1d")
PASSED: dateBetween("01/08/2010", "03/07/2012", "1y 11m 2d")
FAILED: dateBetween("01/08/2010", "11/07/2012", "1y 11m 10d")
java.lang.AssertionError: expected [1y 11m 10d] but found [1y 11m 3d]
...
FAILED: dateBetween("01/08/2010", "21/07/2012", "1y 11m 20d")
java.lang.AssertionError: expected [1y 11m 20d] but found [1y 11m 6d]
...
FAILED: dateBetween("01/08/2010", "31/07/2012", "1y 11m 30d")
java.lang.AssertionError: expected [1y 11m 30d] but found [1y 11m 2d]
...
===============================================
Default test
Tests run: 5, Failures: 3, Skips: 0
===============================================
我使用错误的方法还是在jodatime中出错?
Do I use the wrong method or is it bug in jodatime?
注意:我正在使用jodatime 2.3和testng 6.8.7.
NOTE: I'm using jodatime 2.3 and testng 6.8.7.
推荐答案
不幸的是,乔达时间"中的标准期间类型包括几周(是的-根本不直观,因此仅编写新的期间(从,到")是不够的) ,但是要使用带有明确句点类型参数的替代3-args-constructor,其中您只能指定年,月和日.
Unfortunately the standard period type in Joda Time includes weeks (yes - not intuitive at all, so it is not sufficient just to write new Period(from, to), but to use the alternative 3-args-constructor with an explicit period type argument where you specify only years, months and days.
解决方案:
Period period =
new Period(new LocalDate(start), new LocalDate(end), PeriodType.yearMonthDay());
这篇关于不正确的jodatime时间段-年月日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!