Código de implementación uno:
import java.text.simpledateFormat; import java.util.calendar; import java.util.date; public class dataTestUtil {public static void main (string [] args) lanza la excepción {SimpleDateFormat sdf = new SimpleDateFormat ("yyyymmdd"); Cadena str = "20110823"; Fecha dt = sdf.parse (str); Calendario rightnow = calendar.getInstance (); RightNow.SetTime (DT); rightnow.add (calendar.year, -1); // fecha menos 1 año rightnow.add (calendar.month, 3); // fecha más 3 meses rightnow.add (calendar.day_of_year, 10); // Fecha más 10 días Fecha dt1 = RightNow.getTime (); Cadena restrin = sdf.format (dt1); System.out.println (rest); }}Nota: En el método Agregar del objeto calendario, el segundo parámetro es un número positivo que significa "agregar" y un número negativo que significa "sustracción".
Código 2: Java Date agrega y resta el número de días
Código de clase de prueba:
import java.text.simpledateFormat; import java.util.date; public class dataTest {public static void main (string [] arg) {date ahora = new Date (); addandsubtractdaysbygettime (ahora, -5); addandsubtractdaysbygettime (ahora, 5); addandsubtractdaysbycalendar (ahora, -5); addandsubtractdaysbycalendar (ahora, 5); } Fecha estática pública addandsubtractdaysbygettime (fecha datetime/*date pendiente*/, int n/*days y sustracciones días*/) {// Formato de fecha SimpledateFormat df = new SimpleDateFormat ("yyyyy-mm-dd"); SimpleDateFormat dd = new SimpleDateFormat ("yyyy-mm-dd hh: mm: ss"); System.out.println (df.format (nueva fecha (Datetime.gettime () + n * 24 * 60 * 60 * 1000l))); //System.out.println(dd.format(new date (datetime.gettime () + n * 24 * 60 * 60 * 1000l))); // Tenga en cuenta que debe convertirse a tipo largo aquí, de lo contrario, el desbordamiento de rango ocurrirá cuando N exceda 25, de modo que no pueda obtener la fecha de retorno de la fecha deseada (DateTime.GetTime () + N * 24 * 60 * 60 * 1000L); } Fecha estática pública addandsubtractdaysbycalendar (fecha datetime/*date pendiente*/, int n/*días adicionales y de sustracción*/) {// Formato de fecha SimpledateFormat df = new SimpleDateFormat ("yyyyy-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 (); }} Resultados de ejecución:
2014-10-06
2014-10-16
2014-10-06
2014-10-16
Código tres:
Consulte la información en línea y agregue algunas clases de herramientas sobre la clase de fechas que ha resumido.
paquete com.data.utils; import java.text.simpledateFormat; import java.util.calendar; import java.util.date; public class dateFormat { / *** ¿Cuántos años es la fecha reducida* / public static string dataMinusyear (string str) Exception {simpledateFormat sdf = new -format static (string string string dataMinusyear (string str) Exception {simpledateFormat sdf = new -format static (string string string dataMinusyear (string str) Exception {SimpledateFormat sdf = newformat (new -format (nownformat (public string static ""); Fecha dt = sdf.parse (str); Calendario rightnow = calendar.getInstance (); RightNow.SetTime (DT); rightnow.add (calendar.year, -1); // fecha menos 1 año fecha dt1 = rightnow.gettime (); Cadena restrin = sdf.format (dt1); returnrrt; } / *** Cuántos años se agregarán hasta la fecha* / public static string dataaddyear (string str) lanza la excepción {SimpleDateFormat sdf = new SimpleDateFormat ("yyyymm"); Fecha dt = sdf.parse (str); Calendario rightnow = calendar.getInstance (); RightNow.SetTime (DT); rightnow.add (calendar.year, 1); // fecha más 1 año fecha dt1 = rightnow.gettime (); Cadena restrin = sdf.format (dt1); returnrrt; } / *** ¿Cuántos meses la fecha reduce* / public static string dateminusmonth (string str) lanza excepción {SimpleDateFormat sdf = new SimpleDateFormat ("yyyymm"); Date dt = sdf.parse (str); // generar el calendario de cadena rightnow = calendar.getInstance (); RightNow.setTime (DT); // Establezca la hora de este calendario utilizando la fecha dada. rightnow.add (calendar.month, -1); // fecha menos 1 mes fecha dt1 = rightnow.gettime (); // Devuelve un objeto de fecha que representa el valor de tiempo del calendario. Cadena restrest = sdf.format (dt1); // formatea la fecha dada como una cadena de fecha/hora y agregue el resultado al StringBuffer dado. returnrrt; } / ** * ¿Cuántos meses agrega la fecha * / public static string dateaddmonth (string str) lanza excepción {SimpleDateFormat sdf = new SimpleDateFormat ("yyyymm"); Fecha dt = sdf.parse (str); Calendario rightnow = calendar.getInstance (); RightNow.SetTime (DT); RightNow.Add (calendar.month, 1); // Agregar 3 meses hasta la fecha // rightnow.add (calendar.day_of_year, 10); // fecha más 10 días fecha dt1 = rightnow.gettime (); Cadena restrin = sdf.format (dt1); returnrrt; } / ** * Obtenga STR para el primer mes del año actual y el mes * @param str * 201505 * @return 201501 * @throws excepción * / public static string dateonemonh str = str + "01"; regresar str; } /*** Calcule cuántos meses es el mes seleccionado a partir de enero. * @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); regresar i - j + 1; } / ** * Obtenga la diferencia de tiempo entre dos veces, precisa para milisegundos * @param str * @return * / public static string timEdiferference (inicio largo, extremo largo) {largo entre = end - inicio; día largo = entre / (24 * 60 * 60 * 1000); hora larga = (entre / (60 * 60 * 1000) - día * 24); Min largo = ((entre / (60 * 1000)) - Día * 24 * 60 - Hora * 60); largo s = (entre / 1000 - día * 24 * 60 * 60 - hora * 60 - min * 60); MS largo = (entre - día * 24 * 60 * 60 * 1000 - hora * 60 * 60 * 60 * 1000 - min * 60 * 1000 - S * 1000); Cadena TimediFference = día + "día" + hora + "hora" + min + "minuto" + s + "segundos" + ms + "milisegundos"; return timediFference; }} / ** * Obtenga la hora de inicio de 24 horas, una semana y un mes * * @param TimeInterval *: Day_time_interval Week_time_interval Month_time_interval * @return "yyyy-mm-dd hh: mm: ss" * / public static string getStarttime (int timeval) {calendar cal = calendar.getInstance (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-mm-dd hh: mm: ss"); if (day_time_interval == TimeInterval) {// Obtenga la hora de inicio de 24 horas cal.set (calendar.hour_of_day, 0); cal.set (calendario. Minute, 0); cal.set (calendario. Segundo, 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 (calendario.date, -weekday); cal.set (calendario.hour_of_day, 0); cal.set (calendario. Minute, 0); cal.set (calendario. Segundo, 0); String starttime = sdf.format (cal.gettime ()); Return Starttime; } else if (mes_time_interval == TimeInterval) {int dayOfMonthmin = cal.getActualminimum (calendar.day_of_month); // C.Add (calendar.date, -dayOfMonth); cal.set (calendario.date, dayofmonthmin); cal.set (calendario.hour_of_day, 0); cal.set (calendario. Minute, 0); cal.set (calendario. Segundo, 0); String starttime = sdf.format (cal.gettime ()); Return Starttime; } return null; } / ** * Obtenga el tiempo de finalización de las 24 horas, una semana y un mes * * @param Timeinterval *: Day_time_interval Week_time_interval Month_time_interval * @return "yyyy-mm-dd hh: mm: ss" * / public static string getendtime (int timeval) {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); fecha larga = cal.gettimeinmillis (); Cadena endtime = sdf.format (nueva fecha (fecha)); devolver el tiempo del final; } else if (week_time_interval == TimeInterval) {int WeekDay = cal.get (calendar.day_of_week) - 1; cal.add (calendario.date, -weekday); cal.add (calendario.date, 6); cal.set (calendario.hour_of_day, 23); Cal.set (12, 59); Cal.set (13, 59); fecha larga = cal.gettimeinmillis (); Cadena endtime = sdf.format (nueva fecha (fecha)); devolver el tiempo del final; } else if (mes_time_interval == TimeInterval) {int dayofmonthmax = cal.getActualMaximum (calendar.day_of_month); cal.set (calendario.date, dayofmonthmax); cal.set (calendario.hour_of_day, 23); cal.set (calendario. Minute, 59); Cal.set (calendario. Segundo, 59); Cadena endtime = sdf.format (cal.gettime ()); devolver el tiempo del final; } return null; } /*** Determine si Datstrats está entre Start and End. Tanto el inicio como el final pueden ser null yyyymmddhhmmss o yyyymmdd format * * @author you.xu * @Date 19 de agosto de 2015 a las 3:11:46 pm * @param datestr * @param start * @param end * @return */ public static boolean checkval dateval (string string start, string end) {bo boolean @return */ public static boolean checkval dateval (string string start, string end) {bo boolean; Fecha fecha = nulo; Fecha startdate = null; Date enddate = null; SimpleDateFormat sdf = null; // juzgar formato de fecha if (14 == datestr.length ()) {sdf = new SimpleDateFormat ("yyymmddhhmmss"); } else if (8 == datestr.length ()) {sdf = new SimpleDateFormat ("yyyymmdd"); } else return false; Pruebe {// Cambie la fecha de formato de fecha de juzgar = 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)) // verificar los parámetros para {if (date.compareto (endDate) <= 0) isDateright = true; }} else if ((start! = null) && (end == null)) {try {startDate = sdf.parse (inicio); } 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 (inicio); enddate = sdf.parse (final); } 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; } / ** * Para determinar si Datestr está entre Start and End, tanto Start and End puede estar en formato largo nulo * * @author you.xu * @Date 19 de agosto de 2015 a las 3:12:35 pm * @param datestr * @param start * @param end * @return * / public static boolean checkvatev (string datestrest) fecha larga = -1; décima larga = -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 (numberFormateException nfe) {log.error (nfe, nfe); } if (date <= Todate) {isDateright = true; }} else if ((start! = null) && (end == null)) {try {fromdate = java.lang.long.parselong (inicio); } catch (numberFormateException nfe) {log.error (nfe, nfe); } if (date> = fromDate) {isDateright = true; }} else if ((start! = null) && (end! = null)) {try {todate = java.lang.long.parselong (end); frontDate = java.lang.long.parselong (inicio); } catch (numberFormateException nfe) {log.error (nfe, nfe); } if ((date <= Todate) && (date> = frondate)) {isDateright = true; }} return isDateright; }Estos se usan hasta ahora, y puede agregarlos en cualquier momento. Hay herramientas de tiempo simples y convenientes. Espero aprender contigo, y los señalaré en los comentarios. ¡Gracias! ! !