本文主要是介绍java获取当月日期和周末,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
根据年月,获取当月所有日期
public static void main(String[] args) {System.err.println(getMonthDate("2022-07"));}public static List getMonthDate(String timeStamp){List list = new ArrayList();String[] split = timeStamp.split("-");String year = split[0];String month = split[1];Calendar calendar = Calendar.getInstance();calendar.set(Calendar.YEAR, Integer.parseInt(year));calendar.set(Calendar.MONTH, Integer.parseInt(month) - 1);int day = calendar.getActualMaximum(Calendar.DATE);for (int i = 1; i <= day; i++) {String days = "";if (i<10){days = "0"+i;}else {days = String.valueOf(i);}String aDate = year+"-"+month+"-"+days;list.add(aDate);}return list;}
根据年月,获取当月所有周末
public static void main(String[] args) {System.err.println(getWeekend("2022-07"));}public static List getWeekend(String timeStamp) {List list = new ArrayList();String[] split = timeStamp.split("-");String year = split[0];String month = split[1];Calendar calendar = Calendar.getInstance();calendar.set(Calendar.YEAR, Integer.parseInt(year));calendar.set(Calendar.MONTH, Integer.parseInt(month) - 1);// 设置为当月第一天calendar.set(Calendar.DAY_OF_MONTH, 1);// 当月最大天数int daySize = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);for (int i = 0; i < daySize - 1; i++) {String days = "";//在第一天的基础上加1calendar.add(Calendar.DATE, 1);int week = calendar.get(Calendar.DAY_OF_WEEK);// 1代表周日,7代表周六 判断这是一个星期的第几天从而判断是否是周末if (week == Calendar.SATURDAY || week == Calendar.SUNDAY) {int ct = calendar.get(Calendar.DAY_OF_MONTH);if (ct < 10) {days = "0" + ct;} else {days = String.valueOf(ct);}// 得到当天是一个月的第几天list.add(year + "-" + month + "-" + days);}}return list;}
这篇关于java获取当月日期和周末的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!