Cet article est principalement divisé en deux parties pour le traitement de la date. Voici une introduction détaillée.
Partie 1: Bases du traitement des dattes
Date Classe <Br /> Fonction: La fonction principale consiste à obtenir l'heure actuelle et à convertir la date en un format standard
Date Date = new Date (); SimpledateFormat sdf = new SimpledateFormat ("Yyyy-mm-dd hh: mm: ss"); string str = sdf.format (date); System.out.println ("2015-10-16 14:59:52"); Convertir la chaîne au type de date
String day = "2014-6-5 10:30:30"; SimpledateFormat d2 = new SimpledateFormat ("Yyyy-mm-dd hh: mm: ss"); date date2 = d2.parse (day); System.out.println ("thu juin 05 10:30:30 CST 2014"); Application de classe de calendrier
La classe java.util.calendar est une classe abstraite. Vous pouvez obtenir un objet calendrier en appelant la méthode statique GetInstance (). Cet objet a été initialisé par la date et l'heure actuelles, c'est-à-dire qu'elle représente l'heure actuelle par défaut.
Calendrier c = calendar.getInstance (); int an = c.get (calender.year); int mois = c.get (calender.month) +1; // Obtenez le mois, 0 signifie janvier int day = c.get (calender.day_of_month); int hour = c.get (calender.hour_of_day); int mutte = c.get (calender.Minute); int seconde = c.get (calender.second);
Comparez les 2 mois avec une heure différente
SimpledateFormat Format = new SimpledateFormat ("Yyyy-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 (mois.monthsbetween (d1, d2) .getMonths ()));Partie 2: Classe d'outils de traitement de date
Package com.analysys.website.Control; Importer java.text.parseException; import java.text.paSeposition; import java.text.simpledateFormat; import java.util.calendar; import java.util.date; import java.util.gregoriancalendar; import org.apache.commons.lang.stringutils; import org.apache.log4j.logger; / ** * Classe d'outils de traitement de date * @author dylan_xu * @date 11 mars 2012 * @modified by * @modified date * @Since JDK1.6 * @see com.util.dateutil * / classe publique Dateutil {// ~ Fields statique / initialiseurs // =====================================================================. ====================================================================. Logger statique privé = logger.getLogger (dateUtil.class); chaîne statique privée defaultDatePattern = null; TimePattern de chaîne statique privée = "HH: MM"; calendrier statique privé Cale = calendar.getInstance (); String final statique publique ts_format = dateUtil.getDatePattern () + "hh: mm: ss.s"; / ** DATE FORMAT YYYY-MM String constante * / private static final String Month_format = "yyyy-mm"; / ** DATE FORMAT YYYY-MM-DD String constante * / private static final String date_format = "yyyy-mm-dd"; / ** Format de date HH: mm: SS String constante * / private static final String hour_format = "hh: mm: ss"; / ** DATE FORMAT YYYY-MM-DD HH: MM: SS String constante * / private static final String DateTime_format = "yyyy-mm-dd hh: mm: ss"; / ** Début d'une journée, minute et deuxième string constante 00:00:00 * / private static final String day_begin_string_hhmmss = "00:00:00"; / ** début d'une journée, minute et deuxième chaîne constante 23:59:59 * / public static final string day_end_string_hhmmss = "23:59:59"; Private Static SimpledateFormat sdf_date_format = new SimpledateFormat (date_format); Private Static SimpledateFormat sdf_hour_format = new SimpledateFormat (hour_format); Private Static SimpledateFormat sdf_dateTime_format = new SimpledateFormat (DateTime_Format); // ~ Methods // ==================================================================================================== public DateUtil() { } / ** * Obtenez la date et l'heure actuelles du serveur, retournez sous la forme d'une chaîne de date avec le format: yyyy-mm-dd hh: mm: ss * @author dylan_xu * @date mars 11, 2012 * @return * / public static getDateTime () {try {return sdf_datetime_format.format. } catch (exception e) {logger.debug ("dateUtil.getDateTime ():" + e.getMessage ()); retour ""; }} / ** * Obtenez la date actuelle du serveur, renvoyez sous la forme d'une chaîne de date avec le format: yyyy-mm-dd * @author dylan_xu * @date 11 mars 2012 * @return * / public static string getDate () {try {return sdf_date_format.format (Cale.gettime ()); } catch (exception e) {logger.debug ("dateUtil.getDate ():" + e.getMessage ()); retour ""; }} / ** * Obtenez l'heure actuelle du serveur, renvoyez sous la forme d'une chaîne de date avec le format: HH: MM: SS * @author dylan_xu * @date 11 mars 2012 * @return * / public static string getTime () {String temp = ""; essayez {temp + = sdf_hour_format.format (cale.getTime ()); Tempère de retour; } catch (exception e) {logger.debug ("dateUtil.getTime ():" + e.getMessage ()); retour ""; }} / ** * Valeur par défaut de la date de début pendant les statistiques * @author dylan_xu * @date 11 mars 2012 * @return * / public static static getStartDate () {try {return getyear () + "-01-01"; } catch (exception e) {logger.debug ("dateUtil.getStartDate ():" + e.getMessage ()); retour ""; }} / ** * Valeur par défaut de la date de fin pendant les statistiques * @author dylan_xu * @date 11 mars 2012 * @return * / public static static getEndDate () {try {return getDate (); } catch (exception e) {logger.debug ("dateUtil.gettendDate ():" + e.getMessage ()); retour ""; }} / ** * Obtenez l'année de la date actuelle du serveur * @author dylan_xu * @date 11 mars 2012 * @return * / public static string getyear () {try {return string.valueof (cale.get (calendar.year)); } catch (exception e) {logger.debug ("dateUtil.getyear ():" + e.getMessage ()); retour ""; }} / ** * Obtenez le mois de la date actuelle du serveur * @author dylan_xu * @date 11 mars 2012 * @return * / public static string getMonth () {try {java.text.decimalformat df = new java.text.decimalformat (); df.ApplyPattern ("00; 00"); return df.format ((cale.get (calendar.month) + 1)); } catch (exception e) {logger.debug ("dateUtil.getMonth ():" + e.getMessage ()); retour ""; }} / ** * Obtenez le nombre de jours dans le mois actuel du serveur * @author dylan_xu * @Date 11 mars 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 ()); retour ""; }} / ** * Comparaison du nombre de jours entre deux dates * @author dylan_xu * @date 11 mars 2012 * @param date1 * @param date2 * @return * / public static int getmargin (chaîne date1, chaîne date2) {int margin; essayez {parseposition pos = new parseposition (0); ParsOSITION POS1 = NOUVEAU PARSOSITION (0); DATE DT1 = SDF_DATE_FORMAT.PARSE (DATE1, POS); DATE DT2 = SDF_DATE_FORMAT.PARSE (DATE2, POS1); long l = dt1.gettime () - dt2.getTime (); marge = (int) (l / (24 * 60 * 60 * 1000)); marge de retour; } catch (exception e) {logger.debug ("dateUtil.getmargin ():" + e.toString ()); retour 0; }} / ** * Comparaison du nombre de jours où les deux dates diffèrent * @author dylan_xu * @date 11 mars 2012 * @param date1 * @param date2 * @return * / public static double getDoublergin (String Date1, String Date2) {double marge; essayez {parseposition pos = new parseposition (0); ParsOSITION POS1 = NOUVEAU PARSOSITION (0); Date dt1 = sdf_datetime_format.parse (date1, pos); Date dt2 = sdf_datetime_format.parse (date2, pos1); long l = dt1.gettime () - dt2.getTime (); marge = (l / (24 * 60 * 60 * 1000.00)); marge de retour; } catch (exception e) {logger.debug ("dateUtil.getmargin ():" + e.toString ()); retour 0; }} / ** * Comparaison du nombre de mois entre les deux dates * @author dylan_xu * @date 11 mars 2012 * @param date1 * @param date2 * @return * / public static int getMonthmargin (chaîne date1, chaîne date2) {int margin; try {margin = (Integer.ParseInt (date2.SubString (0, 4)) - Integer.ParseInt (date1.SubString (0, 4))) * 12; margin + = (Integer.ParseInt (date2.SubString (4, 7) .replaceAll ("- 0", "-")) - Integer.Parseint (date1.substring (4, 7) .replaceALL ("- 0", "-")); marge de retour; } catch (exception e) {logger.debug ("dateUtil.getmargin ():" + e.toString ()); retour 0; }} / ** * Renvoyez la date après x jours de date * @author dylan_xu * @date 11 mars 2012 * @param date * @param i * @return * / public static string addday (String Date, int i) {Try {gregorianCalendar gcal = new GregoricanCalendar (enter.parseint (date.substring (0, 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 (exception e) {logger.debug ("dateUtil.addday ():" + e.toString ()); return getDate (); }} / ** * Renvoyez la date après la date plus x mois * @author dylan_xu * @date 11 mars 2012 * @param date * @param i * @return * / public static string addmonth (Date de chaîne, int i) {try {gregoriancalendar gcal = new GregorianCalendar (Integer.ParseInt 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 (); }} / ** * Renvoyez la date après la date plus x ans * @author dylan_xu * @Date 11 mars 2012 * @param date * @param i * @return * / public static string addyear (Date de chaîne, int i) {try {gregoriancalendar gcal = new GregorianCalendar (Integer.ParseInt 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 (exception e) {logger.debug ("dateUtil.addyear ():" + e.toString ()); retour ""; }} / ** * Renvoyez le jour maximum d'un certain mois dans une certaine année * @author dylan_xu * @Date 11 mars 2012 * @param année * @param mois * @return * / public static int getmaxday (int iyear, int image) {int day = 0; try {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; } jour de retour; } catch (exception e) {logger.debug ("dateUtil.getMonthday ():" + e.toString ()); retour 1; }} / ** * Date de format * @author dylan_xu * @date 11 mars 2012 * @param orgdate * @param type * @param span * @return * / @suppresswarnings ("static-access") public string rolldate (string orgdate, int int iyear, image, 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); } image--; if (imonth <0 || image> 11) {image = 0; } iday = Integer.ParseInt (temp); if (jour <1 || iday> 31) iday = 1; Calendar orgCale = calendar.getInstance (); orgCale.set (iyear, image, iday); temp = this.rolldate (orgcale, type, span); Tempère de retour; } catch (exception e) {return ""; }} public static String rollDate (calendar cal, int type, int span) {try {string temp = ""; Calendrier Rolcale; rolcale = cal; rolcale.add (type, span); temp = sdf_date_format.format (rolcale.getTime ()); Tempère de retour; } catch (exception e) {return ""; }} / ** * Renvoie le format de date par défaut * @author dylan_xu * @date 11 mars 2012 * @return * / public static synchronisé String getDatePattern () {defaultDatePattern = "yyyy-mm-dd"; return defaultDatePattern; } / ** * Remplacez la date spécifiée en une chaîne au format et sortie par défaut, telles que: yyyy-mm-dd * @author dylan_xu * @date le 11 mars 2012 * @param adate * @return * / public static String getDate (date adet) {SimpledateFormat df = null; String returnValue = ""; if (adate! = null) {df = new SimpledateFormat (getDatePattern ()); returnValue = df.format (adate); } return (returnValue); } / ** * Obtenez la chaîne de temps pour la date donnée, le format est le format de temps par défaut actuel * @author dylan_xu * @Date 11 mars 2012 * @param thetime * @return * / public static string gettimeNow (date theTetime) {return getDatetime (timePattern, thetime); } / ** * Obtenez l'objet de calendrier du calendrier pour l'heure actuelle * @author dylan_xu * @Date 11 mars 2012 * @return * @throws parseException * / public Calendar getToday () lève ParseException {Date Today = new Date (); SimpledateFormat df = new SimpledateFormat (getDatePattern ()); String TodayAsstring = df.format (aujourd'hui); Calendrier cal = new GregorianCalendar (); cal.settime (convertsstringTodate (aujourd'huiassstring)); Retour Cal; } / ** * Convertir la classe de date en un formulaire de chaîne au format spécifié * @author dylan_xu * @date 11 mars 2012 * @param amask * @param adate * @return * / public static final string getDateTime (String amask, date adate) {SimpleDateFormat df = null; String returnValue = ""; if (adate == null) {logger.error ("adate est null!"); } else {df = new SimpledateFormat (Amask); returnValue = df.format (adate); } return (returnValue); } / ** * Convertir la date spécifiée au formulaire de chaîne au format par défaut * @author dylan_xu * @date 11 mars 2012 * @param adate * @return * / public static final string convertDateToString (date adate) {return getDatetime (getDatePattern (), adate); } / ** * Convertissez la chaîne de date au type de date au format spécifié * @author dylan_xu * @date 11 mars 2012 * @param amask le format de date spécifié, tel que: yyyy-mm-dd * @param stradate de date à convertir * @return * @throws parseException * / public static date convertstringtodate. ParseException {SimpledateFormat df = null; Date de date = null; df = new SimpledateFormat (Amask); if (logger.isdebugeNabled ()) {logger.debug ("Converting '" + strdate + "' à ce jour avec mask '" + amask + "'"); } try {date = df.parse (strdate); } catch (parseException pe) {logger.error ("parseException:" + pe); jeter PE; } return (date); } / ** * Convertir la chaîne de date à Date Type dans le format par défaut * @author dylan_xu * @Date 11 mars 2012 * @param strdate * @return * @throws parseException * / public static date convertsstringtodate (String stradate) lance parseException {date adate = null; essayez {if (logger.isdebugeNable ()) {logger.debug ("Conversion de la date avec le modèle:" + getDatePattern ()); } adate = convertsstringTodate (getDatePattern (), strdate); } catch (parseException pe) {logger.error ("n'a pas pu convertir '" + strdate + "' en une date, lancer une exception"); Jetez une nouvelle parseException (pe.getMessage (), pe.getErroroffset ()); } return adate; } / ** * Renvoie une chaîne de date de type simple de Java * @author dylan_xu * @date 11 mars 2012 * @return * / public static static getImpledateFormat () {SimpledateFormat formatter = new SimpledateFormat (); String ndateTime = Formatter.Format (new Date ()); retour ndatetime; } / ** * Comparaison de la date au format de chaîne spécifié avec l'heure actuelle * @Author Dylan * @Date 17 février 2012 * @param Strdate le temps nécessaire pour comparer * @return * <p> * Int Code * <ul> * <li> -1 Temps actuel <Comparez Temps </li> * <li> 0 Temps de comparaison </li> * * <li>> = 1CURRENT </ul> * </p> * / public static int compareToCurtime (string strdate) {if (stringUtils.isblank (strdate)) {return -1; } Date curtime = cale.gettime (); String strCurtime = null; essayez {strCurtime = sdf_datetime_format.format (curtime); } catch (exception e) {if (logger.isdebugeNable ()) {logger.debug ("[ne peut pas formater '" + strdate + "' à une date, lançant l'exception:" + e.getLocalizedMessage () + "]"); }} if (stringUtils.isnotblank (strCurtime)) {return strcurtime.compareto (strdate); } return -1; } / ** * Ajouter un temps minimum à la date de requête * * @param Type de type Tible Date * @Param Le paramètre de conversion Date * @return * / @SuppressWarnings ("Deprécation") Date statique publique AddStartTime (Date Param) {Date Date = Param; essayez {date.sethours (0); date.setMinutes (0); Date.SetSeconds (0); date de retour; } catch (exception ex) {date de retour; }} / ** * Ajouter un maximum de temps à la date de requête * * @param Type Type Date * @param Le paramètre de conversion Date * @return * / @SuppressWarnings ("Deprécation") Public Static Date Addendtime (Date Param) {Date Date = Param; essayez {date.sethours (23); Date.SetMinutes (59); Date.SetSeconds (0); date de retour; } catch (exception ex) {date de retour; }} / ** * Renvoie le nombre de jours dans l'année en cours du système * * @param mois * @return Total Days in the Specificed Mois * / @SuppressWarnings ("Deprécation") public static static getMonThlastDay (int mois) {date date = new Date (); 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 an = date.getyear () + 1900; if (année% 4 == 0 && an% 100! = 0 || an% 400 == 0) {Retour Day [1] [mois] + ""; } else {return day [0] [mois] + ""; } } /** * 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 (année% 4 == 0 && an% 100! = 0 || an% 400 == 0) {Retour Day [1] [mois] + ""; } else {return day [0] [mois] + ""; }} / ** * juger si c'est une année normale ou une année de saut * @author dylan_xu * @date 11 mars 2012 * @param année * @return * / public static booléen isleapyear (int an) {if (an% 4 == 0 && an%! = 0) || (an% 400) == 0) {return true; } else {return false; }} / ** * Obtenez le tampon du jour de l'heure actuelle * @author dylan_xu * @date 11 mars 2012 * @return * / @suppresswarnings ("dépréciation") String statique public gettimestamp () {date date = cale.gettime (); String TimeStamp = "" + (date.getyear () + 1900) + date.getMonth () + Date.getDate () + date.getMinutes () + Date.getSeconds () + Date.getTime (); horodatage de retour; } / ** * Obtenez le tampon de jour de l'heure spécifiée * * @return * / @SuppressWarnings ("Deprécation") String statique public gettimestamp (date de date) {TimeStamp de chaîne = "" + (date.getyear () + 1900) + Date.getMonth () + Date.getDate () + Date.getMinutes () + Date.getSeconds () + Date.getMinutes () + Date.getSeconds () +. horodatage de retour; } public static void main (String [] args) {System.out.println (getyear () + "|" + getMonth () + "|" + getDate ()); }}Ce qui précède concerne cet article, j'espère qu'il sera utile à l'apprentissage de tout le monde.