Joda 时间库 getdays 给出错误结果
Joda time library getdays giving wrong result
public static void main(String args[]) throws ParseException{
String string = "May 2, 2016";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
DateTime dateTime = new DateTime(date);
DateTime currentDate = new DateTime(Calendar.getInstance().getTime());
System.out.println(Calendar.getInstance().getTime());
Period p = new Period(dateTime, currentDate);
System.out.println(p.getYears());
System.out.println(p.getMonths());
System.out.println(p.getDays());
}
}
几天的结果是 1
考虑到今天是 2016 年 6 月 10 日,预计应该是 8 点
这里没有错,你得到 1,因为 8 天是一周零一天。如果你想为 "day" 获得 8,你必须从周部分(即周 * 7 + 天)计算它。
要获得您期望的结果,您应该使用另一个 PeriodType
:PeriodType.yearMonthDay()
。
Period p = new Period(dateTime, currentDate, PeriodType.yearMonthDay());
目前您的代码使用标准(默认)PeriodType
,它将周期分为年、月、周、日、小时、分钟、秒、毫秒。
public static void main(String args[]) throws ParseException{
String string = "May 2, 2016";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
DateTime dateTime = new DateTime(date);
DateTime currentDate = new DateTime(Calendar.getInstance().getTime());
System.out.println(Calendar.getInstance().getTime());
Period p = new Period(dateTime, currentDate);
System.out.println(p.getYears());
System.out.println(p.getMonths());
System.out.println(p.getDays());
}
}
几天的结果是 1
考虑到今天是 2016 年 6 月 10 日,预计应该是 8 点
这里没有错,你得到 1,因为 8 天是一周零一天。如果你想为 "day" 获得 8,你必须从周部分(即周 * 7 + 天)计算它。
要获得您期望的结果,您应该使用另一个 PeriodType
:PeriodType.yearMonthDay()
。
Period p = new Period(dateTime, currentDate, PeriodType.yearMonthDay());
目前您的代码使用标准(默认)PeriodType
,它将周期分为年、月、周、日、小时、分钟、秒、毫秒。