【发布时间】:2018-06-18 04:57:20
【问题描述】:
我试图找出两个特定日期的日历日期列表。但我只能在同一年内确定两个日期。
我做了什么:
private ArrayList<Calendar> weekendList = null;
public void findWeekendsList(long startDate, long endDate)
{
weekendList = new ArrayList();
Calendar calendarStart = null;
Calendar calendarEnd=null;
calendarStart= Calendar.getInstance();
calendarStart.setTimeInMillis(startDate);
/*calendarEnd= Calendar.getInstance();
calendarEnd.setTimeInMillis(endDate);
*/
// The while loop ensures that you are only checking dates in the current year
while(calendar.get(Calendar.YEAR) == Calendar.getInstance().get(Calendar.YEAR)){
// The switch checks the day of the week for Saturdays and Sundays
switch(calendar.get(Calendar.DAY_OF_WEEK)){
case Calendar.SATURDAY:
case Calendar.SUNDAY:
weekendList.add(calendar);
break;
}
// Increment the day of the year for the next iteration of the while loop
calendar.add(Calendar.DAY_OF_YEAR, 1);
}
}
我有 102 个周末,就像 1 月 9 日到 12 月 31 日,但我想从今天(2018 年 1 月 9 日)到明年(比如 2019 年 1 月 9 日),所有周末都在 arrayList 中。
如果有人有任何想法,那对我会有很大帮助。
【问题讨论】:
-
取当前的
Date,将年份增加1,这将成为目标结束日期——类似于this——但我会使用更新的日期/时间API跨度> -
您的
while条件似乎错误,应该更像while (calendar.getTime().before(toDate)) {,其中toDate在您要检查的最后一个Date之后 -
另外,因为
Calendar是可变的,添加calendar将简单地生成一个具有相同日期的值列表 -
另外,从技术上讲,因为您同时添加了
Saturday和Sunday,所以您每个“周末”的天数会减少
标签: java datetime calendar weekday