Implementation code one:
import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class DateTestUtil { public static void main(String[] args) throws Exception { SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd"); String str="20110823"; Date dt=sdf.parse(str); Calendar rightNow = Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.YEAR,-1);//Date minus 1 year rightNow.add(Calendar.MONTH,3);//Date plus 3 months rightNow.add(Calendar.DAY_OF_YEAR,10);//Date plus 10 days Date dt1=rightNow.getTime(); String reStr = sdf.format(dt1); System.out.println(reStr); }}Note: In the add method of the Calendar object, the second parameter is a positive number that means "add", and a negative number that means "subtraction".
Code 2: java date adds and subtracts the number of days
Test class code:
import java.text.SimpleDateFormat; import java.util.Date; public class DateTest { public static void main(String[] arg){ Date now = new Date(); addAndSubtractDaysByGetTime(now,-5); addAndSubtractDaysByGetTime(now,5); addAndSubtractDaysByCalendar(now,-5); addAndSubtractDaysByCalendar(now,5); } public static Date addAndSubtractDaysByGetTime(Date dateTime/*pending date*/,int n/*addition and subtraction days*/){ //Date format SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat dd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(df.format(new Date(dateTime.getTime() + n * 24 * 60 * 60 * 1000L))); //System.out.println(dd.format(new Date(dateTime.getTime() + n * 24 * 60 * 60 * 1000L))); //Note that you must convert to Long type here, otherwise the range overflow will occur when n exceeds 25, so that you cannot get the desired date value return new Date(dateTime.getTime() + n * 24 * 60 * 60 * 1000L); } public static Date addAndSubtractDaysByCalendar(Date dateTime/*Pending date*/,int n/*Additional and subtraction days*/){ //Date format SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat dd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Calendar calstart = java.util.Calendar.getInstance(); calstart.setTime(dateTime); calstart.add(java.util.Calendar.DAY_OF_WEEK, n); System.out.println(df.format(calstart.getTime())); //System.out.println(dd.format(calstart.getTime())); return calstart.getTime(); } } Running results:
2014-10-06
2014-10-16
2014-10-06
2014-10-16
Code Three:
Check the information online and add some tool classes about the Date class that you have summarized.
package com.data.utils;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class DateFormat { /** * How many years is the date reduced*/ public static String dateMinusYear(String str) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); Date dt = sdf.parse(str); Calendar rightNow = Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.YEAR, -1);// Date minus 1 year Date dt1 = rightNow.getTime(); String reStr = sdf.format(dt1); return reStr; } /** * How many years to add to date*/ public static String dateAddYear(String str) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); Date dt = sdf.parse(str); Calendar rightNow = Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.YEAR, 1);// Date plus 1 year Date dt1 = rightNow.getTime(); String reStr = sdf.format(dt1); return reStr; } /** * How many months does the date reduce*/ public static String dateMinusMonth(String str) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); Date dt = sdf.parse(str);//Generate the string Calendar rightNow = Calendar.getInstance(); rightNow.setTime(dt);//Set the time of this Calendar using the given Date. rightNow.add(Calendar.MONTH, -1);// Date minus 1 month Date dt1 = rightNow.getTime();// Returns a Date object representing the Calendar time value. String reStr = sdf.format(dt1);//Format the given Date as a date/time string and add the result to the given StringBuffer. return reStr; } /** * How many months does the date add */ public static String dateAddMonth(String str) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); Date dt = sdf.parse(str); Calendar rightNow = Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.MONTH, 1);// Add 3 months to date// rightNow.add(Calendar.DAY_OF_YEAR,10);//Date plus 10 days Date dt1 = rightNow.getTime(); String reStr = sdf.format(dt1); return reStr; } /** * Get str for the first month of the current year and month * @param str * 201505 * @return 201501 * @throws Exception */ public static String dateOneMonth(String str) { str = str.substring(0, str.length() - 2); str = str + "01"; return str; } /** * Calculate how many months the selected month is from January. * @param str 201509 * @return 9 */ public static int dateDistanceMonth(String str) { int i = Integer.parseInt(str); int j = Integer.parseInt(DateFormat.dateOneMonth(str)); System.out.println(i - j); return i - j + 1; } /** * Get the time difference between two times, accurate to milliseconds* @param str * @return */ public static String TimeDifference(long start, long end) { long between = end - start; long day = between / (24 * 60 * 60 * 1000); long hour = (between / (60 * 60 * 1000) - day * 24); long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60); long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 - min * 60); long ms = (between - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000); String timeDifference = day + "day" + hour + "hour" + min + "minute" + s + "seconds" + ms + "milliseconds"; return timeDifference; }} /** * Get the start time of 24 hours, one week, and one month* * @param timeInterval * : DAY_TIME_INTERVAL WEEK_TIME_INTERVAL MONTH_TIME_INTERVAL * @return "yyyy-mm-dd hh:mm:ss" */ public static String getStartTime(int timeInterval) { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (DAY_TIME_INTERVAL == timeInterval) {// Get the 24-hour start time cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); String startTime = sdf.format(cal.getTime()); return startTime; } else if (WEEK_TIME_INTERVAL == timeInterval) { int weekday = cal.get(Calendar.DAY_OF_WEEK) - 1; cal.add(Calendar.DATE, -weekday); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); String startTime = sdf.format(cal.getTime()); return startTime; } else if (MONTH_TIME_INTERVAL == timeInterval) { int dayofmonthMin = cal.getActualMinimum(Calendar.DAY_OF_MONTH); // c.add(Calendar.DATE, -dayofmonth); cal.set(Calendar.DATE, dayofmonthMin); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); String startTime = sdf.format(cal.getTime()); return startTime; } return null; } /** * Get the end time of 24 hours, one week, and one month* * @param timeInterval * : DAY_TIME_INTERVAL WEEK_TIME_INTERVAL MONTH_TIME_INTERVAL * @return "yyyy-mm-dd hh:mm:ss" */ public static String getEndTime(int timeInterval) { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("GMT+8")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (DAY_TIME_INTERVAL == timeInterval) { cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(12, 59); cal.set(13, 59); long date = cal.getTimeInMillis(); String endTime = sdf.format(new Date(date)); return endTime; } else if (WEEK_TIME_INTERVAL == timeInterval) { int weekday = cal.get(Calendar.DAY_OF_WEEK) - 1; cal.add(Calendar.DATE, -weekday); cal.add(Calendar.DATE, 6); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(12, 59); cal.set(13, 59); long date = cal.getTimeInMillis(); String endTime = sdf.format(new Date(date)); return endTime; } else if (MONTH_TIME_INTERVAL == timeInterval) { int dayOfMonthMax = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DATE, dayOfMonthMax); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); String endTime = sdf.format(cal.getTime()); return endTime; } return null; } /** * Determine whether dateStr is between start and end. Both start and end can be null yyyyMMddHHmmss or yyyyMMdd format* * @author you.xu * @date August 19, 2015 at 3:11:46 pm * @param dateStr * @param start * @param end * @return */ public static boolean checkDateVal(String dateStr, String start, String end) { boolean isDateRight = false; Date date = null; Date startDate = null; Date endDate = null; SimpleDateFormat sdf = null; // Judge date format if (14 == dateStr.length()) { sdf = new SimpleDateFormat("yyyMMddHHmmss"); } else if (8 == dateStr.length()) { sdf = new SimpleDateFormat("yyyyMMdd"); } else return false; try { // Change the judge date format date = sdf.parse(dateStr); } catch (ParseException e) { log.error(e, e); } if ((start == null) && (end != null)) { try { endDate = sdf.parse(end); } catch (ParseException ex1) { log.error(ex1, ex1); } if ((date != null) && (endDate != null))// Check parameters for { if (date.compareTo(endDate) <= 0) isDateRight = true; } } else if ((start != null) && (end == null)) { try { startDate = sdf.parse(start); } catch (ParseException ex1) { log.error(ex1, ex1); } if ((date != null) && (startDate != null)) { if (date.compareTo(startDate) >= 0) isDateRight = true; } } else if ((start != null) && (end != null)) { try { startDate = sdf.parse(start); endDate = sdf.parse(end); } catch (ParseException ex2) { System.out.println(ex2.toString()); } if ((startDate != null) && (date != null) && (endDate != null)) { if ((date.compareTo(startDate) >= 0) && (date.compareTo(endDate) <= 0)) isDateRight = true; } } return isDateRight; } /** * To determine whether dateStr is between start and end, both start and end can be in null long format* * @author you.xu * @date August 19, 2015 at 3:12:35 pm * @param dateStr * @param start * @param end * @return */ public static boolean checkDateV(String dateStr, String start, String end) { boolean isDateRight = false; long date = -1; long fromDate = -1; long toDate = -1; date = java.lang.Long.parseLong(dateStr); if ((start == null) && (end == null)) { isDateRight = true; } else if ((start == null) && (end != null)) { try { toDate = java.lang.Long.parseLong(end); } catch (NumberFormatException nfe) { log.error(nfe, nfe); } if (date <= toDate) { isDateRight = true; } } else if ((start != null) && (end == null)) { try { fromDate = java.lang.Long.parseLong(start); } catch (NumberFormatException nfe) { log.error(nfe, nfe); } if (date >= fromDate) { isDateRight = true; } } else if ((start != null) && (end != null)) { try { toDate = java.lang.Long.parseLong(end); fromDate = java.lang.Long.parseLong(start); } catch (NumberFormatException nfe) { log.error(nfe, nfe); } if ((date <= toDate) && (date >= fromDate)) { isDateRight = true; } } return isDateRight; }These are used so far, and you can add them at any time. There are simple and convenient time tools. I hope to learn with you, and I will point them out in the comments. Thanks! ! !