本文主要是介绍Java获取前N天的日期(Calendar类),前N天与当前日期的差值并去除周末(双休日),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Java获取前N天的日期(Calendar类),前N天与当前日期的差值并去除周末(双休日)
@Testpublic void test(){Calendar calendar = Calendar.getInstance();calendar.setTime(new Date());System.out.println(calendar.getTime());//当前日期calendar.add(Calendar.DAY_OF_YEAR,-4);//如果是查未来几天,去除"-"System.out.println(calendar.getTime());//4天前日期int difference=differentDays(calendar.getTime(),new Date());System.out.println(difference);//去除周末后的差值}/**工具:去除周末工具*beforeDate 开始日期*currentDate 结束日期*/public static int differentDays(Date beforeDate, Date currentDate) {Calendar cl1 = Calendar.getInstance();Calendar cl2 = Calendar.getInstance();cl1.setTime(beforeDate);cl2.setTime(currentDate);int count = 0;while (cl1.compareTo(cl2) <= 0) {if (cl1.get(Calendar.DAY_OF_WEEK) != 7 && cl1.get(Calendar.DAY_OF_WEEK) != 1)count++;cl1.add(Calendar.DAY_OF_MONTH, 1);}return count;}
result:
这篇关于Java获取前N天的日期(Calendar类),前N天与当前日期的差值并去除周末(双休日)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!