import java.util.Calendar; import java.util.Date; public class AddDate { public static Date addDate(Date date, int dayNum) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_YEAR, dayNum); return calendar.getTime(); } public static Date addMonth(Date date, int monthNum) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, monthNum); return calendar.getTime(); } public static void main(String[] arg) { Date old_date = new Date(); Date add_day = addDate(old_date, -10); Date add_month = addMonth(old_date, 1); System.out.println("old_date=" + old_date + ", add_day=" + add_day + ", add_month=" + add_month); } }
public static int getWeekday(Date date){ int dayOfWeek = 0; Calendar cal = Calendar.getInstance(); cal.setTime(date); dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1; if (dayOfWeek == 0) { dayOfWeek = 7; } return dayOfWeek; }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Main { public static int getWeekday(Date date){ int dayOfWeek = 0; Calendar cal = Calendar.getInstance(); cal.setTime(date); dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1; if (dayOfWeek == 0) { dayOfWeek = 7; } return dayOfWeek; } final static String[] weekHoliday = new String[]{"0527 母亲节", "0637 父亲节", "0744 感恩节"}; public static void main(String[] arg) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); int year = 2015; for (int month=1; month<=12; month++) { int day_num = 31; if (month == 2) { day_num = 28; } else if (month==4 || month==6 || month==9 || month==11) { day_num = 30; } for (int day=1; day<=day_num; day++) { for(int k = 0; k < weekHoliday.length; k++){ int weeknum = (day-1) / 7; if (day-weeknum*7 > 0) { weeknum++; } Date date = sdf.parse(String.format("%d%02d%02d", year, month, day)); //返回公历节假日名称 String wd = weekHoliday[k].split(" ")[0]; //节假日的日期 String wdv = weekHoliday[k].split(" ")[1]; //节假日的名称 String wmd = String.format("%02d%d%d", month, weeknum, getWeekday(date)); if(wd.equals(wmd)){ System.out.printf("%d年%d月%d日是%s\n", year, month, day, wdv); } } } } } }
点击这里下载本文实现的日历源码