Today in doing the project, met the requirements for addition and subtraction of time to operate, according to the date string passed in the operating parameters ( "+", "-"), addend (the number of days to be operated), of date addition and subtraction operations, the query data, wrote a Demo class test, debug normal by subtraction, now share the code below, I hope to help friends encountered!
Package com.ltw.test; Import the java.text.SimpleDateFormat; Import java.util.Date; Import a java.util.GregorianCalendar; public class the Test { @SuppressWarnings ( "deprecation" ) public static void main (String [] args) { // the passed date string, the operating parameters ( "+", "-"), addend (days to be operated), the operation of subtraction date string dateStr = "2020-03-26 18:20: "23 ; // (- being given a string is Date.parse (), alternatively may be implemented through such discovery belt '') into the format of the original time string str = dateStr.replace (" - " ," / " ); // add and subtract time type String operator ="+"; //Plus or minus the number of days Integer = 20 is I ; // custom variable reception time conversion value Long J = 0 ; a Date DATE = null ; the try { J = Date.parse (STR); DATE = new new a Date (J); } the catch ( E Exception) { e.printStackTrace (); } the GregorianCalendar GC = new new the GregorianCalendar (); gc.setTime (DATE); IF ( "+" .equals (operator)) { gc.add (GregorianCalendar.DATE, I); } else if ("-".equals(operator)) { gc.add(GregorianCalendar.DATE, (-i)); } Date a = gc.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(sdf.format(a)); } }
For more exciting content, learning materials, videos, etc., please pay attention to micro-channel public number [Style] programmer, reply keywords.