永发信息网

java 计算两日期之间有多少天双休

答案:3  悬赏:10  手机版
解决时间 2021-03-22 17:39
  • 提问者网友:溺爱和你
  • 2021-03-21 19:26
java 计算两日期之间有多少天双休
最佳答案
  • 五星知识达人网友:怙棘
  • 2021-03-21 20:50

public static int getSundayNum(String startDate, String endDate, String format) {
List yearMonthDayList = new ArrayList();
Date start = null, stop = null;
try {
start = new SimpleDateFormat(format).parse(startDate);
stop = new SimpleDateFormat(format).parse(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
if (start.after(stop)) {
Date tmp = start;
start = stop;
stop = tmp;
}
//将起止时间中的所有时间加到List中
Calendar calendarTemp = Calendar.getInstance();
calendarTemp.setTime(start);
while (calendarTemp.getTime().getTime() <= stop.getTime()) {
yearMonthDayList.add(new SimpleDateFormat(format)
.format(calendarTemp.getTime()));
calendarTemp.add(Calendar.DAY_OF_YEAR, 1);
}
Collections.sort(yearMonthDayList);
int num=0;//周六,周日的总天数
int size=yearMonthDayList.size();
int week=0;
for (int i = 0; i < size; i++) {
String day=(String)yearMonthDayList.get(i);
System.out.println(day);
week=getWeek(day, format);
if (week==6||week==0) {//周六,周日
num++;
}
}
return num;
}

public static int getWeek(String date, String format) {
Calendar calendarTemp = Calendar.getInstance();
try {
calendarTemp.setTime(new SimpleDateFormat(format).parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
int i = calendarTemp.get(Calendar.DAY_OF_WEEK);
int value=i-1;//0-星期日
// System.out.println(value);
return value;
}
public static void main(String[] args) {
int i=getSundayNum("2013-03-01", "2013-03-20", "yyyy-MM-dd");
System.out.println(i);
}
全部回答
  • 1楼网友:一把行者刀
  • 2021-03-21 22:26
单纯计算?意义不是很大,因为我国还会调休的
  • 2楼网友:第四晚心情
  • 2021-03-21 21:32
public static int getWeekends(Date d1, Date d2){ if(d1 == null || d2 == null){ return 0; } int count = 0; Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(d1); c2.setTime(d2); // 保证第二个时间一定大于第一个时间 if (c1.after(c2)) { c2.setTime(d1); c1.setTime(d2); } // 当日期c2在日期c1之后退出循环 while(c2.after(c1)){ if(c1.get(Calendar.DAY_OF_WEEK) == 1 || c1.get(Calendar.DAY_OF_WEEK) == 7){ System.out.println(c1.getTime()); count++ ; } // 天数加1 c1.set(Calendar.DAY_OF_YEAR, (c1.get(Calendar.DAY_OF_YEAR) + 1)); } return count; }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯