Este artículo se divide principalmente en dos partes para el procesamiento de fechas. Aquí hay una introducción detallada.
Parte 1: Conceptos básicos del procesamiento de fechas
Función de clase de fecha <Br />: la función principal es obtener la hora actual y convertir la fecha en un formato estándar
Fecha fecha = nueva fecha (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-mm-dd hh: mm: ss"); string str = sdf.format (fecha); system.out.println ("2015-10-16 14:59:52"); Convertir el tipo de cadena hasta la fecha
String day = "2014-6-5 10:30:30"; SimpleDateFormat d2 = new SimpleDateFormat ("yyyy-mm-dd hh: mm: ss"); date2 = d2.parse (day); system.out.println ("Jun 05 10:30:30 CST 2014"); Aplicación de clase calendario
La clase java.util.calendar es una clase abstracta. Puede obtener un objeto calendario llamando al método estático getInstance (). Este objeto ha sido inicializado por la fecha y hora actuales, es decir, representa la hora actual de forma predeterminada.
Calendario c = calendar.getInstance (); int año = c.get (calender.year); int mes = c.get (calender.month) +1; // Obtener el mes, 0 significa enero int day = C.get (calender.day_of_month); int hour = c.get (calender.hour_of_day); int mind = c.get (calender.minute); int segundo = c.get (calender.second);
Compare los 2 meses con un tiempo diferente
SimpleDateFormat Format = new SimpleDateFormat ("yyyyy-mm-dd hh: mm: ss"); dateTime d1 = new DateTime (Format.Parse ("2016-10-31 00:00:00")); Datetime D2 = New Datetime (Format.Parse ("2015-1-31 00:00:00 ")); System.out.println (math.abs (mess.monthsbetween (d1, d2) .getmonths ()));Parte 2: Clase de herramienta de procesamiento de fechas
paquete com.analysys.website.control; import java.text.parseException; import java.text.parseposition; import java.text.simpledateFormat; import java.util.calendar; import java.util.date; import java.util.gregoriancalendar; importar org.apache.commons.lang.stringutils; import org.apache.log4j.logger; /** * Clase de herramienta de procesamiento de fechas * @author dylan_xu * @date marzo de marzo de 2012 * @modified por * @modified fecha * @since jdk1.6 * @see com.util.dateutil */public class dateutil {// ~ campos estáticos/inicializadores // ======================================================================================================================== ======================================================================================================================== Private static logger logger = logger.getLogger (dateUtil.class); cadena estática privada defaultDatePattern = null; TIMEPTERN de cadena estática privada = "HH: MM"; Calendario estático privado CALE = calendar.getInstance (); Public static final String ts_format = dateUtil.getDatePattern () + "HH: MM: SS.S"; / ** Formato de fecha YYYY-MM Cadena constante*/ private static final cadena mes_format = "yyyy-mm"; / ** Formato de fecha YYYYY-MM-DD String Constant*/ private static final String date_format = "yyyy-mm-dd"; / ** Formato de fecha HH: MM: SS String Constant*/ private static final String Hour_format = "HH: MM: SS"; / ** FORMATO DE FECHA YYYYY-MM-DD HH: MM: SS String Constant*/ private static final String datetime_format = "yyyy-mm-dd HH: mm: ss"; / ** Inicio de un día, minuto y segunda cadena constante 00:00:00*/ Private static final String Day_begin_string_hhmmss = "00:00:00"; / ** Inicio de un día, minuto y segunda cadena constante 23:59:59*/ public static final String day_end_string_hhmmss = "23:59:59"; privado static simpledateFormat sdf_date_format = new SimpleDateFormat (date_format); static static private simpledateFormat sdf_hour_format = new SimpleDateFormat (Hour_Format); privado static simpledateFormat sdf_datetime_format = new SimpleDateFormat (datetime_format); // ~ Methods // ==================================================================================================== public DateUtil() { } / ** * Obtenga la fecha y hora actuales del servidor, regrese en forma de una cadena de fechas con el formato: aaa yyyy-mm-dd hh: mm: ss * @author dylan_xu * @date mar 11 de 2012 * @return * / public static string getDateTime () {trey {return sdf_datetime_format.format (CeCal.gettime (); } catch (Exception e) {logger.debug ("dateUtil.getDateTime ():" + e.getMessage ()); devolver ""; }} / ** * Obtenga la fecha actual del servidor, regrese en forma de una cadena de fecha con el formato: aaa yyyy-mm-dd * @author dylan_xu * @date mar 11, 2012 * @return * / public static string getDate () {try {return sdf_date_format.format (cale.gettime ()); } catch (excepción e) {logger.debug ("dateUtil.getDate ():" + e.getMessage ()); devolver ""; }} / ** * Obtenga la hora actual del servidor, regrese en forma de una cadena de fecha con el formato: HH: MM: SS * @author dylan_xu * @Date Mar 11, 2012 * @return * / public static string gettime () {string temp = ""; intente {temp += sdf_hour_format.format (cale.gettime ()); regresar temp; } catch (excepción e) {logger.debug ("dateUtil.gettime ():" + e.getMessage ()); devolver ""; }} / ** * Valor predeterminado de la fecha de inicio durante las estadísticas * @author dylan_xu * @date mar 11 de 2012 * @return * / public static string getStartDate () {try {return getyear () + "-01-01"; } catch (Exception e) {logger.debug ("dateUtil.getStartDate ():" + E.getMessage ()); devolver ""; }} / ** * Valor predeterminado de la fecha de finalización durante las estadísticas * @author dylan_xu * @date marzo de marzo de 2012 * @return * / public static string getenddate () {try {return getDate (); } catch (Exception e) {logger.debug ("dateUtil.getendDate ():" + e.getMessage ()); devolver ""; }} / ** * Obtenga el año de la fecha actual del servidor * @author dylan_xu * @date marzo de marzo de 2012 * @return * / public static string getyear () {try {return string.valueOf (Cale.get (calendar.year)); } catch (Exception e) {logger.debug ("dateUtil.getyear ():" + e.getMessage ()); devolver ""; }} / ** * Obtenga el mes de la fecha actual del servidor * @author dylan_xu * @date marzo de 2012 * @return * / public static string getMonth () {try {java.text.decimalformat df = new java.text.decimalformat (); df.AplyPattern ("00; 00"); return df.Format ((Cale.get (calendario.month) + 1)); } catch (Exception e) {logger.debug ("dateUtil.getMonth ():" + e.getMessage ()); devolver ""; }} / ** * Obtenga el número de días en el mes actual del servidor * @author dylan_xu * @date marzo de marzo de 2012 * @return * / public static string getday () {try {return string.valueOf (cale.get (calendar.day_of_month); } catch (Exception e) {logger.debug ("dateUtil.getday ():" + e.getMessage ()); devolver ""; }} / ** * Comparación del número de días entre dos fechas * @author dylan_xu * @date marzo de marzo de 2012 * @param date1 * @param date2 * @return * / public static int getmargin (string date1, cadena date2) {int margin; intente {parsePosition pos = new ParsePosition (0); Parseposition pos1 = nueva parseposition (0); Fecha dt1 = sdf_date_format.parse (date1, pos); Fecha dt2 = sdf_date_format.parse (date2, pos1); long l = dt1.gettime () - dt2.gettime (); margen = (int) (l / (24 * 60 * 60 * 1000)); margen de regreso; } Catch (Exception e) {logger.debug ("dateUtil.getMargin ():" + e.ToString ()); regresar 0; }} / ** * Comparación del número de días en que las dos fechas difieren * @author dylan_xu * @date mar 11 de marzo de 2012 * @param date1 * @param date2 * @return * / public static double getDoufblemargin (string date1, string date2) {doble margen; intente {parsePosition pos = new ParsePosition (0); Parseposition pos1 = nueva parseposition (0); Fecha dt1 = sdf_datetime_format.parse (date1, pos); Fecha dt2 = sdf_datetime_format.parse (date2, pos1); long l = dt1.gettime () - dt2.gettime (); margen = (l / (24 * 60 * 60 * 1000.00)); margen de regreso; } Catch (Exception e) {logger.debug ("dateUtil.getMargin ():" + e.ToString ()); regresar 0; }} / ** * Comparación del número de meses entre las dos fechas * @author dylan_xu * @date mar 11 de marzo de 2012 * @param date1 * @param date2 * @return * / public static int getMonthmargin (string date1, string date2) {int margen; Pruebe {margin = (integer.parseInt (date2.substring (0, 4)) - integer.parseInt (date1.substring (0, 4))) * 12; margen += (integer.parseInt (date2.substring (4, 7) .replaceAll ("-0", "-"))-integer.parseInt (date1.substring (4, 7) .replaceall ("-0", "-"))); margen de regreso; } Catch (Exception e) {logger.debug ("dateUtil.getMargin ():" + e.ToString ()); regresar 0; }} / ** * Devuelve la fecha después de x días de fecha * @author dylan_xu * @date marzo de 2012 * @param fecha * @param i * @return * / public static string addday (date de cadena, int i) {try {GregorInCalendar gcal = new Gregoriastendar (integer.parseint (date.Substring (0, 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4), 4). Integer.ParseInt (date.substring (5, 7)) - 1, integer.parseInt (date.substring (8, 10))); gcal.add (Gregoriancalendar.Date, i); return sdf_date_format.format (gcal.gettime ()); } catch (excepción e) {logger.debug ("dateUtil.addday ():" + e.ToString ()); return getDate (); }} / ** * Devuelve la fecha después de la fecha más x meses * @author dylan_xu * @date marzo de 2012 * @param fecha * @param i * @return * / public static string addmonth (string date, int i) {intent {gregoriancAnDar gcal = new GregoriancInCalendar (integer.parseint (date.substring (0, 4), 0, 4), 0, 4), 0, 4), 0, 4), 0, 4), 0, 4). Integer.ParseInt (date.substring (5, 7)) - 1, integer.parseInt (date.substring (8, 10))); gcal.add (Gregoriancalendar.Month, i); return sdf_date_format.format (gcal.gettime ()); } catch (Exception e) {logger.debug ("dateUtil.addmonth ():" + e.ToString ()); return getDate (); }} / ** * Devuelva la fecha después de la fecha más x años * @author dylan_xu * @date marzo de 2012 * @param fecha * @param i * @return * / public static string addyear (string date, int i) {intent {GregoriancAnDar gcal = new GregoriancInEndeN Integer.ParseInt (date.substring (5, 7)) - 1, integer.parseInt (date.substring (8, 10))); gcal.add (Gregoriancalendar.Year, i); return sdf_date_format.format (gcal.gettime ()); } catch (excepción e) {logger.debug ("dateUtil.addyear ():" + e.ToString ()); devolver ""; }} / ** * Devuelve el día máximo de un determinado mes en cierto año * @author dylan_xu * @date mar 11 de marzo de 2012 * @param año * @param mes * @return * / public static int getmaxday (int iyear, int Image) {int day = 0; Pruebe {if (iMonth == 1 || Image == 3 || Image == 5 || Image == 7 || Image == 8 || Image == 10 || Image == 12) {Day = 31; } else if (iMonth == 4 || Image == 6 || Image == 9 || Image == 11) {Day = 30; } else if ((0 == (iyear % 4)) && (0! = (iyear % 100)) || (0 == (iYear % 400))) {day = 29; } else {day = 28; } día de regreso; } Catch (Exception e) {logger.debug ("dateUtil.getMonthday ():" + e.ToString ()); regresar 1; }} / ** * Fecha de formato * @author dylan_xu * @date marzo de 2012 * @param orgdate * @param type * @param span * @return * / @supesswarnings ("static-access") public string rollDate (string orgdate, int type, int span) {try {string temp = ";"; "; int iyear, imagen, iday; int iPos = 0; char seperater = '-'; if (orgdate == null || orgdate.length () <6) {return ""; } iPos = orgdate.indexof (seperater); if (iPOS> 0) {iYear = integer.ParseInt (orgdate.substring (0, iPOS)); temp = orgdate.substring (iPOS + 1); } else {iYear = Integer.ParseInt (orgdate.substring (0, 4)); temp = orgdate.substring (4); } iPos = temp.IndexOf (Seperater); if (iPOS> 0) {image = integer.ParseInt (temp.substring (0, iPOS)); temp = temp.substring (iPOS + 1); } else {iPOS = temp.IndexOf (Seperater); if (iPOS> 0) {image = integer.ParseInt (temp.substring (0, iPOS)); temp = temp.substring (iPOS + 1); } else {image = integer.parseInt (temp.substring (0, 2)); temp = temp.substring (2); } imagen--; if (imonth <0 || imagen> 11) {imagen = 0; } iday = integer.parseInt (temp); if (día <1 || iday> 31) iday = 1; Calendario orgcale = calendar.getInstance (); orgcale.set (iyear, imagen, iday); temp = this.rollDate (orgial, type, span); regresar temp; } catch (Exception e) {return ""; }} public static string rOllDate (calendar cal, int type, int span) {try {string temp = ""; Calendario rolcale; rolcale = cal; rolcale.add (tipo, span); temp = sdf_date_format.format (rolcale.gettime ()); regresar temp; } catch (Exception e) {return ""; }} / ** * Devuelve el formato de fecha predeterminado * @author dylan_xu * @date mar 11 de 2012 * @return * / public static sincronizado string getDatePattern () {defaultDatePattern = "yyyy-mm-dd"; return DefaultDatePattern; } / ** * Sustituya la fecha especificada en una cadena en el formato y salida predeterminados, como: aaa yyyy-mm-dd * @author dylan_xu * @date mar 11 de marzo de 2012 * @param adate * @return * / public static final string getDate (date adate) {simplifeFormat df = null; Cadena returnValue = ""; if (adate! = null) {df = new SimpleDateFormat (getDatePattern ()); returnValue = df.format (adate); } return (returnValue); } / ** * Obtenga la cadena de tiempo para la fecha dada, el formato es el formato de tiempo predeterminado actual * @author dylan_xu * @date marzo de marzo de 2012 * @param thetime * @return * / public static string getTimenow (date thetime) {return getDatEtime (TimePattern, Thetime); } / ** * Obtenga el objeto calendario de calendario para la hora actual * @author dylan_xu * @date marzo de marzo de 2012 * @return * @throws parseException * / public calendar getToday () lanza parseException {fecha hoy = nueva fecha (); SimpleDateFormat df = new SimpleDateFormat (getDatePattern ()); String hoyString = df.format (hoy); Calendario cal = new Gregoriancalendar (); Cal.setTime (ConvertStringTodate (TodayString)); devolver Cal; } / ** * Convierta la clase de fecha en un formulario de cadena en el formato especificado * @author dylan_xu * @date marzo de marzo de 2012 * @param amask * @param adate * @return * / public static final string getDateTime (string amask, date adate) {SimpleDateFormat df = null; Cadena returnValue = ""; if (adate == null) {logger.error ("¡ADATE es nulo!"); } else {df = new SimpleDateFormat (amask); returnValue = df.format (adate); } return (returnValue); } / ** * Convierta la fecha especificada en el formulario de cadena en el formato predeterminado * @author dylan_xu * @date marzo de marzo de 2012 * @param adate * @return * / public static final converdateToString (date adate) {return getDateTime (getDatePattern (), adate); } / ** * Convierta la cadena de fecha en el tipo de fecha en el formato especificado * @author dylan_xu * @date marzo de 2012 * @param amask el formato de fecha especificado, como: aayyy-mm-dd * @param Strdate la cadena de fecha para ser convertida * @return * @throws parseexception * / public fallet final estático convertir averttingtodate (string amask, stilts). ParseException {SimpleDateFormat df = null; Fecha fecha = nulo; df = new SimpleDateFormat (amask); if (logger.isDebugeNabled ()) {logger.debug ("convertir '" + strdate + "' hasta la fecha con la máscara '" + amask + "'"); } try {date = df.parse (strdate); } catch (parseException PE) {logger.error ("parseException:" + pe); arrojar educación física; } retorno (fecha); } / ** * Convertir la cadena de fecha a la fecha tipo en el formato predeterminado * @author dylan_xu * @date marzo de 2012 * @param strdate * @return * @throws parseException * / public static date ConvertStringTodate (String strdate) tira parseException {fecha adate = null; Pruebe {if (logger.isdeBugeNabled ()) {logger.debug ("Convertir fecha con el patrón:" + getDatePtern ()); } adate = ConvertStringTodate (getDatePattern (), strdate); } Catch (ParseException PE) {logger.error ("no pudo convertir '" + strdate + "' a una fecha, lanzando excepción"); tirar nueva ParseException (PE.GetMessage (), PE.GetErrorOffset ()); } return adate; } / ** * Devuelve una cadena de fecha de Java Simple Type * @author dylan_xu * @Date Mar 11 de 2012 * @return * / public static string getSimpledateFormat () {simpledateFormat formatter = new SimpledateFormat (); Cadena ndateTime = formatter.format (nueva fecha ()); regresar ndatetime; }/** * Comparación de la fecha en el formato de cadena especificado con la hora actual * @author dylan * @Date Feb, 2012 * @param strdate el tiempo requerido para comparar * @return * <p> * int code * <ul> * <ri> -1 hora actual <compare tiempo </li> * <li> 0 tiempo actual = comparar tiempo </li> * * <li>> = 1current Time <compare </li> * * <li> 0 TIEMPO Current = Compara TIEMPO </li> * * <Li>> = 1 CECURA </ul> * </p> */public static int compareTocurTime (String strdate) {if (stringUtils.isblank (strdate)) {return -1; } Date curtime = cale.gettime (); Cadena strcurtime = null; intente {strcurtime = sdf_datetime_format.format (curtime); } catch (Exception e) {if (logger.isDebugeNabled ()) {logger.debug ("[no se puede formatear '" + strdate + "' a una fecha, lanzando excepción:" + e.getLocalizedMessage () + "]"); }} if (stringUtils.isnotblank (strcurtime)) {return strcurtime.compareto (strdate); } return -1; } / ** * Agregue una hora mínima a la fecha de consulta * * @param Tipo de destino Fecha * @param Parámetro de conversión Fecha * @return * / @SupessWarnings ("Deprecation") Public Static Date AddStartTime (Fecha Param) {fecha date = param; intente {date.sethours (0); date.setMinutes (0); date.setSeconds (0); Fecha de devolución; } capt (excepción ex) {fecha de retorno; }} / ** * Agregue tiempo máximo a la fecha de consulta * * @param Tipo de destino Fecha * @param Parámetro de conversión Fecha * @return * / @supesswarnings ("deprecation") fecha estática pública addendtime (date param) {fecha fecha = param; intente {date.sethours (23); date.setMinutes (59); date.setSeconds (0); Fecha de devolución; } capt (excepción ex) {fecha de retorno; }} / *** Devuelve el número de días en el año actual*** @param mes* @return Total Days en el mes especificado* / @supesswarnings ("deprecation") public static string getMonthlastday (int mes) {fecha de fecha = nueva fecha (); int [] [] day = {{0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 30, 31, 30, 31}}; int año = date.getyear () + 1900; if (año % 4 == 0 && año % 100! = 0 || año % 400 == 0) {Día de retorno [1] [mes] + ""; } else {Day de retorno [0] [mes] + ""; } } /** * Return the number of days in the specified month in the specified year* * @param Year year * @param Month month * @return Total days in the specified month*/ public static String getMonthLastDay(int year, int month) { int[][] day = { { 0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31}}; if (año % 4 == 0 && año % 100! = 0 || año % 400 == 0) {Día de retorno [1] [mes] + ""; } else {Day de retorno [0] [mes] + ""; }} / ** * Juzgue si es un año normal o un año bisiesto * @author dylan_xu * @date marzo de 2012 * @param año * @return * / public static boolean isleapyear (int año) {if ((año % 4 == 0 && año 100! = 0) || (año % 400) == 0) {regreso verdadero; } else {return false; }} / ** * Obtenga el sello de día de la hora actual * @author dylan_xu * @date marzo de marzo de 2012 * @return * / @supesswarnings ("deprecation") public static string getTimestamp () {fecha date = cale.gettime (); String timestamp = "" + (date.getyear () + 1900) + date.getMonth () + date.getDate () + date.getminutes () + date.getSeconds () + date.getTime (); Return Timestamp; } / ** * Obtenga el sello de día de la hora especificada * * @return * / @suppleswarnings ("deprecation") public static string getTimestamp (fecha date) {string timestamp = "" + (date.getyear ()) + 1900) + date.getMonth () + date.getDate () + date.getMinutes () + date.getSeconds () + date. () ();); Return Timestamp; } public static void main (string [] args) {system.out.println (getyear () + "|" + getMonth () + "|" + getDate ()); }}Lo anterior se trata de este artículo, espero que sea útil para el aprendizaje de todos.