Java adds and subtracts the date Date class the year the month the time difference and so on

  • 2020-05-26 08:36:39
  • OfStack

Implementation code 1:


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 years 
  rightNow.add(Calendar.MONTH,3);// The date and 3 months 
  rightNow.add(Calendar.DAY_OF_YEAR,10);// The date and 10 day 
  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 positive for "plus" and negative for "minus".

Code 2: java date date plus or minus 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/* Date to be processed */,int n/* Add and subtract the number */){ 
      
     // The 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 there 1 It has to be converted into Long Type, or n More than 25 A range overflow occurs and you do not get the desired date value  
     return new Date(dateTime.getTime() + n * 24 * 60 * 60 * 1000L); 
   } 
    
   public static Date addAndSubtractDaysByCalendar(Date dateTime/* Date to be processed */,int n/* Add and subtract the number */){ 
      
     // The 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(); 
   } 
 
}

Operation results:
2014-10-06
2014-10-16
2014-10-06
2014-10-16

Code 3:

Look it up on the Internet and add your own summary of the Date tools.


package com.data.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateFormat {

 /**
  *  Date minus a few years 
  */
 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 years 
  Date dt1 = rightNow.getTime();
  String reStr = sdf.format(dt1);
  return reStr;
 }

 /**
  *  Date plus years 
  */
 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);//  The date and 1 years 
  Date dt1 = rightNow.getTime();
  String reStr = sdf.format(dt1);
  return reStr;
 }

 /**
  *  Subtract a few months from the date 
  */
 public static String dateMinusMonth(String str) throws Exception {

  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
  Date dt = sdf.parse(str);// Generate the string Date
  Calendar rightNow = Calendar.getInstance();
  rightNow.setTime(dt);// Using a given  Date  Set this  Calendar  The time.  
  rightNow.add(Calendar.MONTH, -1);//  Date minus 1 months 
  Date dt1 = rightNow.getTime();// return 1 A said this  Calendar  The time value of  Date  Object. 
  String reStr = sdf.format(dt1);// Will be given  Date  Formatted as a date / Time string and add the result to the given  StringBuffer . 
  return reStr;
 }

 /**
  *  Date plus months 
  */
 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);//  The date and 3 months 
  // rightNow.add(Calendar.DAY_OF_YEAR,10);// The date and 10 day 
  Date dt1 = rightNow.getTime();
  String reStr = sdf.format(dt1);
  return reStr;
 }

 /**
  *  Gets the date of the current month 1 Months of str
  * @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;
 }

 /**
  *  Figure out the distance of the selected month 1 Months have months. 
  * @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 the 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 * 60 - min * 60);
  long ms = (between - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000
    - min * 60 * 1000 - s * 1000);
  String timeDifference = day + " day " + hour + " hours " + min + " points " + s + " seconds " + ms
    + " ms ";
  return timeDifference;
 }
}

 /**
  *  To obtain 24 Hours, 1 Weeks, 1 Month starting time 
  * 
  * @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) {//  To obtain 24 Hour starting 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;
 }

 /**
  *  To obtain 24 Hours, 1 Weeks, 1 End of 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;
 }
 /**
  *  judge dateStr Whether in start and end In the middle, start and end Can be for null yyyyMMddHHmmss or yyyyMMdd format 
  * 
  * @author you.xu
  * @date 2015 years 8 month 19 On the afternoon 3:11:46
  * @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;
  //  Determine the date format 
  if (14 == dateStr.length()) {
   sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  } else if (8 == dateStr.length()) {
   sdf = new SimpleDateFormat("yyyyMMdd");
  } else
   return false;

  try {
   //  Change the date determination 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;
 }

 /**
  *  judge dateStr Whether in start and end In the middle, start and end Can be for null long Image format 
  * 
  * @author you.xu
  * @date 2015 years 8 month 19 On the afternoon 3:12:35
  * @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;
 }

So far, I have used these, and I can add them at any time. There is a simple and convenient time tool class. I hope to learn from you, and I will point out in the comments. thanks!!!!!!


Related articles: