一尘不染

如何获得一年的开始和结束日期?

java

我必须使用Java Date类来解决此问题(它与我无法控制的内容进行接口)。

如何获得一年的开始和结束日期,然后遍历每个日期?


阅读 716

收藏
2020-12-03

共1个答案

一尘不染

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, 1);    
Date start = cal.getTime();

//set date to last day of 2014
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 11); // 11 = december
cal.set(Calendar.DAY_OF_MONTH, 31); // new years eve

Date end = cal.getTime();

//Iterate through the two dates 
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
    gcal.add(Calendar.DAY_OF_YEAR, 1);
    //Do Something ...
}
2020-12-03