Code d'implémentation ONE:
Importer java.text.simpledateFormat; import java.util.calendar; import java.util.date; public class DateTestutil {public static void main (string [] args) lève exception {simpledateFormat sdf = new simpleateFormat ("yyyymmdd"); String str = "20110823"; Date dt = sdf.parse (str); Calendar Rightnow = calendar.getInstance (); RightNow.SetTime (DT); Rightnow.Add (calendar.year, -1); // date moins 1 an Rightnow.Add (Calendar.month, 3); // Date plus 3 mois Rightnow.Add (Calendar.Day_of_year, 10); // Date plus 10 jours Dt1 = RightNow.GetTime (); String rest (sdf.format (dt1); System.out.println (retenue); }}Remarque: Dans la méthode ADD de l'objet calendrier, le deuxième paramètre est un nombre positif qui signifie "ajouter" et un nombre négatif qui signifie "soustraction".
Code 2: la date Java ajoute et soustrait le nombre de jours
Code de classe de test:
import java.text.simpledateFormat; Importer java.util.date; classe publique DateTest {public static void main (String [] arg) {date now = new Date (); addandSubtractdaysByGetTime (maintenant, -5); AddandSubtractDaySByGetTime (maintenant, 5); AddandSubtractdaysByCalendar (maintenant, -5); AddandSubtractdaysByCalendar (maintenant, 5); } Public Static Date addandSubtractDaysByGetTime (Date DateTime / * Date en attente * /, int n / * Addition et Soutraction 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))); // Notez que vous devez vous convertir en type long ici, sinon le débordement de plage se produira lorsque n dépassera 25, afin que vous ne puissiez pas obtenir la valeur de date de date souhaitée nouvelle date (datetime.gettime () + n * 24 * 60 * 60 * 1000l); } Public Static Date addandSubtractdaysByCalendar (date DateTime / * Date en attente * /, int n / * jours supplémentaires et de soustraction * /) {// Format de date 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 (); }} Résultats en cours:
2014-10-06
2014-10-16
2014-10-06
2014-10-16
Code trois:
Consultez les informations en ligne et ajoutez quelques classes d'outils sur la classe de date que vous avez résumé.
Package com.data.utils; import java.text.simpledateformat; import java.util.calendar; import java.util.date; public class dateformat {/ ** * Combien d'années est la date réduite * / public static dateminusyear (string st) lance une exception {simpledate sdf = new Simleate ("yyyymmmmmmmmmmmmmmmmmmmmmmye); Date dt = sdf.parse (str); Calendar Rightnow = calendar.getInstance (); RightNow.SetTime (DT); Rightnow.Add (calendar.year, -1); // Date moins 1 an date dt1 = reightnow.getTime (); String rest (sdf.format (dt1); return rest; } / ** * Combien d'années à ajouter à la date * / public static string dataEaddyear (String str) lève l'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 an DT1 = Rightnow.getTime (); String rest (sdf.format (dt1); return rest; } / ** * Combien de mois la date réduit * / public static String dateminusmonth (String Str) lève l'exception {SimpledateFormat sdf = new SimpledateFormat ("yyyymm"); DATE DT = SDF.Parse (Str); // Générez le calendrier de chaîne Rightnow = Calendar.getInstance (); RightNow.SetTime (DT); // Définissez l'heure de ce calendrier en utilisant la date donnée. Rightnow.Add (Calendar.month, -1); // Date moins 1 mois Date DT1 = Rightnow.getTime (); // Renvoie un objet de date représentant la valeur d'heure du calendrier. String restR = sdf.format (dt1); // formate la date donnée en tant que chaîne de date / heure et ajoutez le résultat au stringbuffer donné. return rest; } / ** * Combien de mois la date ajoute * / public static String dataEaddMonth (String str) lève l'exception {SimpledateFormat sdf = new SimpledateFormat ("yyyymm"); Date dt = sdf.parse (str); Calendar Rightnow = calendar.getInstance (); RightNow.SetTime (DT); Rightnow.add (calendar.month, 1); // ajouter 3 mois à ce jour // reightnow.add (calendar.day_of_year, 10); // date plus 10 jours dt1 = reightnow.gettime (); String rest (sdf.format (dt1); return rest; } / ** * Obtenez STR pour le premier mois de l'année et du mois en cours * @param str * 201505 * @return 201501 * @throws exception * / public static String dateOnemonth (String str) {str = str.substring (0, str.length () - 2); str = str + "01"; retour STR; } / ** * Calculer le nombre de mois du mois sélectionné à partir de janvier. * @param str 201509 * @return 9 * / public static int dadestanceMem (String str) {int i = Integer.parseInt (str); int J = Integer.ParseInt (dateFormat.DateOneMem (STR)); System.out.println (i - j); retour i - j + 1; } / ** * Obtenez la différence de temps entre deux fois, précise à des millisecondes * @param str * @return * / public static String TimeDifférence (Long Start, Long End) {Long Between = end - start; long jour = entre / (24 * 60 * 60 * 1000); longue heure = (entre / (60 * 60 * 1000) - jour * 24); long min = ((entre / (60 * 1000)) - jour * 24 * 60 - heure * 60); long s = (entre / 1000 - jour * 24 * 60 * 60 - heure * 60 - min * 60); long ms = (entre - jour * 24 * 60 * 60 * 1000 - heure * 60 * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000); String TimeDifférence = Day + "Day" + Hour + "Hour" + Min + "Minute" + S + "Seconds" + MS + "millisecondes"; Retour TimeDifférence; }} / ** * Obtenez l'heure de début de 24 heures, une semaine et un mois * * @param timeInterval *: day_time_interval week_time_interval mens_time_interval * @return "yyyy-mm-dd hh: mm: ss" * / public static string getStarttime (int timeInterval) {calendar calise = calendar.get.getance ();); SimpledateFormat sdf = new SimpledateFormat ("yyyy-mm-dd hh: mm: ss"); if (day_time_interval == TimeInterval) {// Obtenez l'heure de début 24 heures 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 (mois_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; } / ** * Obtenez l'heure de fin de 24 heures, une semaine et un mois * * @param timeInterval *: day_time_interval week_time_interval mens_time_interval * @return "yyyy-mm-dd hh: mm: ss" * / public static string getTime (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); date longue = cal.getTimeInmillis (); String EndTime = SDF.Format (nouvelle date (date)); Retour Fndtime; } 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); date longue = cal.getTimeInmillis (); String EndTime = SDF.Format (nouvelle date (date)); Retour Fndtime; } else if (mois_time_interval == timeInterval) {int dayofmonthmax = cal.getactualmaxim (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 ()); Retour Fndtime; } return null; } / ** * Déterminez si Datestr est entre le début et la fin. Le début et la fin peuvent être nuls yyyymmddhhmms ou format yyyymmdd * * @author you.xu * @date 19 août 2015 à 3:11:46 PM * @param datestr * @param start * @param end * @return * / public static boolean checkDateval (String Datestr start, string end) {booolean nataterwat = false; Date de date = null; Date startDate = null; Date EndDate = null; SimpledateFormat sdf = null; // Juge Date Format if (14 == Datestr.Length ()) {sdf = new SimpledateFormat ("yyymmddhhmmss"); } else if (8 == Datestr.Length ()) {sdf = new SimpledateFormat ("yyyymmdd"); } else return false; Essayez {// Modifier la date du juge Date de format = sdf.parse (datestr); } catch (paSeException 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)) // Vérifiez les paramètres pour {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)) isDaterright = true; }} return isDateRight; } / ** * Pour déterminer si Datestr est entre le début et la fin, le démarrage et la fin peuvent être au format Null Long * * @author you.xu * @Date 19 août 2015 à 3:12:35 PM * @param Datestr * @param start * @param end * @return * / public static boolean checkdatev (String Datestr, string start, fin) {boolean natateright = false; date longue = -1; Long Frodate = -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); FrodAD = java.lang.long.parselong (start); } catch (NumberFormatexception nfe) {log.Error (nfe, nfe); } if ((date <= todate) && (date> = FromDate)) {isDateRight = true; }} return isDateRight; }Ceux-ci sont utilisés jusqu'à présent et vous pouvez les ajouter à tout moment. Il existe des outils temporels simples et pratiques. J'espère apprendre avec vous et je les signalerai dans les commentaires. Merci! ! !