日历之间的Java期间
问题描述:
对于Java程序,我需要2个日期的Timeperiod,但是我得到的Period.Class错误。日历之间的Java期间
我试着用Period.between
Calendar myCalendar = new GregorianCalendar(2017, Calendar.JANUARY,1);
Calendar myPeriod = new GregorianCalendar(2017, Calendar.MARCH, 1);
Period prd = Period.between(myCalendar, myPeriod);
return prd.getTime();
我用来返回myCalendar.getTime();
现在我需要的myCalendar
和myPeriod
“周期” 来获得TIMEPERIOD。
谢谢。
答
如果您使用的是Java 8,则Period
接受2 LocalDate
参数(在official documentation中阅读更多关于它的内容)。
这是代码,如果你还需要从Calendar
到LocalDate
转换:
Calendar myCalendar = new GregorianCalendar(2017, Calendar.JANUARY,1);
Calendar myPeriod = new GregorianCalendar(2017, Calendar.MARCH, 1);
LocalDate start = Instant.ofEpochMilli(myCalendar.getTimeInMillis()).atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate end = Instant.ofEpochMilli(myPeriod.getTimeInMillis()).atZone(ZoneId.systemDefault()).toLocalDate();
否则,只需直接创建2个LocalDate
变量:
LocalDate start = LocalDate.of(2017, Month.JANUARY, 1);
LocalDate end = LocalDate.of(2017, Month.MARCH, 1);
,然后计算它们之间的时间段:
Period prd = Period.between(start, end);
System.out.println(prd.toString()); //P2M
y有什么错误你得到了吗?该方法的签名'between'示出,它预计LocalDates,不日程表 –
在型周期(LOCALDATE,LOCALDATE)之间的方法是不适用于参数(日历,日历)用于错误 和 之间 在.getTime –
上,类型Period的getTime()方法未定义您可以阅读[如何将日历转换为LocalDate](https://kodejava.org/how-do-i-convert-between-old-date-and -calendar-object-with-new-java-8-date-time /)或使用LocalDate的其他工厂方法。 –