如何在Java中获取当前日期和其他日期(java.util.Date)之间的差异
我有传入的java.util.Date对象,我需要知道它们之间有多少年.
我尝试了Joda的时间段,但我必须创建joda的时间对象.有没有其他方法来计算这种差异.获得毫升并尝试将其转换为年份的方法并不算闰年.
由于Date不推荐使用该类中的大多数方法,因此可以使用java.util.Calendar.
Calendar firstCalendar = Calendar.getInstance();
firstCalendar.setTime(firstDate); //set the time as the first java.util.Date
Calendar secondCalendar = Calender.getInstance();
secondCalendar.setTime(secondDate); //set the time as the second java.util.Date
int year = Calendar.YEAR;
int month = Calendar.MONTH;
int difference = secondCalendar.get(year) - firstCalendar.get(year);
if (difference > 0 &&
(secondCalendar.get(month) < firstCalendar.get(month))) {
difference--;
}
Run Code Online (Sandbox Code Playgroud)
随着if声明,我正在检查我们是否有日期June, 2011和March, 2012(全年差异为0).当然,我假设secondDate是后 firstDate.
| 归档时间: |
|
| 查看次数: |
5087 次 |
| 最近记录: |