Dieser Artikel ist hauptsächlich in zwei Teile für die Verarbeitung der Datumsaufnahme unterteilt. Hier ist eine detaillierte Einführung.
Teil 1: Grundlagen der Datumsverarbeitung
Datum der Klasse <BR /> Funktion: Die Hauptfunktion besteht darin, die aktuelle Zeit zu erhalten und das Datum in ein Standardformat umzuwandeln
Datum Datum = neues Datum (); SimpleDateFormat SDF = new SimpledateFormat ("yyyy-mm-dd hh: mm: ss"); String str = sdf.format (Datum); System.out.println ("2015-10-16 14:59:52"); Konvertieren Sie die Zeichenfolge zum Datumstyp
String Day = "2014-6-5 10:30:30"; SimpleDateFormat D2 = new SimpledateFormat ("yyyy-mm-dd hh: mm: ss"); Datum2 = d2.Parse (Tag); System.out.println ("Thu Jun 05 10:30:30 cst 2014"); Kalenderklassenanwendung
Die Java.util.Calendar -Klasse ist eine abstrakte Klasse. Sie können ein Kalenderobjekt erhalten, indem Sie die statische Methode getInstance () aufrufen. Dieses Objekt wurde nach dem aktuellen Datum und der aktuellen Uhrzeit initialisiert, dh es stellt die aktuelle Zeit standardmäßig dar.
Kalender c = calendar.getInstance (); int Jahr = C.Get (calender.year); int monat = c.get (calender.month) +1; // den Monat erhalten, 0 bedeutet Januar int Day = C.Get (Calender.day_of_month); int Hour = C.Get (calender.hour_of_day); int minute = cget (calender.minute); int Second = C.Get (Calender.second);
Vergleichen Sie die 2 Monate mit unterschiedlicher Zeit
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-1-311111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111:" 00:00:00 ")); System.out.println (math.abs (Monate.monthsbetween (d1, d2) .getmonths ());Teil 2: Datumsverarbeitungstoolklasse
Paket com.analyys.website.control; importieren java.text.parseException; import java.text.parseposition; 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; /** * Datumsverarbeitungstoolklasse * @Author Dylan_xu * @date 11. März 2012 * @Modified By * @Modified Date * @Since Jdk1.6 * @see com.util.dateutil */Public Class Datumutil {// ~ statische Fields/Initializer // =========================================================================== =========================================================================== privater statischer Logger logger = logger.getLogger (dateUtil.class); private statische Zeichenfolge defaultDatePattern = null; private statische String timePattern = "HH: mm"; privater statischer Kalender cale = calendar.getInstance (); public static final String ts_format = dateUtil.getDatePattern () + "HH: mm: ss.s"; / ** Datumsformat yyyy-mm String konstant*/ privat static Final String monat_format = "yyyy-mm"; / ** Datumsformat yyyy-mm-dd String konstant*/ privat static Final String date_format = "yyyy-mm-dd"; / ** Datumsformat HH: MM: SS -String -Konstante*/ private statische String -Stunde_Format = "HH: MM: SS"; / ** Datumsformat yyyy-mm-dd hh: mm: ss String konstant*/ private statische String String datetime_format = "Yyyy-Mm-dd HH: mm: ss"; / ** Start eines Tages, Minute und zweiter String konstant 00:00:00*/ Private Static Final String Day_Begin_string_hhmmss = "00:00:00"; / ** Start eines Tages, Minute und zweiter String Konstante 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() { } / ** * Holen Sie sich das aktuelle Datum und die Uhrzeit des Servers, kehren Sie in Form eines Datumszeichens mit dem Format zurück: yyyy-mm-dd hh: mm: ss * @author dylan_xu * @date mar 11, 2012 * @return * / public static String getDateTime () {try {tret {trink sdf_datetime_format.format. } catch (Ausnahme e) {logger.debug ("dateUtil.getDatetime ():" + e.getMessage ()); zurückkehren ""; }} / ** * Erhalten Sie das aktuelle Datum des Servers, kehren Sie in Form eines Datumszeichens mit dem Format zurück: yyyy-mm-dd * @author dylan_xu * @date mar 11, 2012 * @return * / public static String getdate () {try {return sdf_date_format.format.format (cale.getime); } catch (Ausnahme e) {logger.debug ("dateUtil.getDate ():" + e.getMessage ()); zurückkehren ""; }} / ** * Die aktuelle Zeit des Servers erhalten, kehren Sie in Form eines Datumszeichens mit dem Format zurück: HH: mm: ss * @author dylan_xu * @date mar 11, 2012 * @return * / public static String getTime () {String temp = ""; try {temp += sdf_hour_format.format (cale.getTime ()); Temperatur zurückgeben; } catch (Ausnahme e) {logger.debug ("dateUtil.getTime ():" + e.getMessage ()); zurückkehren ""; }} / ** * Standardwert des Startdatums während der Statistik * @Author dylan_xu * @date 11. März 2012 * @return * / public static String getStartDate () {try {return getyear () + "-01-01"; } catch (Ausnahme e) {logger.debug ("dateUtil.getStartDate ():" + e.getMessage ()); zurückkehren ""; }} / ** * Standardwert des Enddatums während der Statistik * @Author Dylan_xu * @date 11. März 2012 * @return * / public static String getendDate () {try {return getDate (); } catch (Ausnahme e) {logger.debug ("dateUtil.getendDate ():" + e.getMessage ()); zurückkehren ""; }} / ** * Erhalten Sie das Jahr des aktuellen Datums des Servers * @Author Dylan_xu * @date 11. März 2012 * @return * / public static String getyear () {try {return string.valueof (cale.get (calendar.year)); } catch (Ausnahme e) {logger.debug ("dateUtil.getyear ():" + e.getMessage ()); zurückkehren ""; }} / ** * Erhalten Sie den Monat des aktuellen Datums des Servers * @Author dylan_xu * @date 11. März 2012 * @return * / public static String getMonth () {try {java.text.decimalformat df = new java.text.decimalformat (); df.appyprenner ("00; 00"); return df.Format ((cale.get (Kalender.month) + 1)); } catch (Ausnahme e) {logger.debug ("dateUtil.getMonth ():" + e.getMessage ()); zurückkehren ""; }} / ** * Erhalten Sie die Anzahl der Tage im aktuellen Monat des Servers * @Author Dylan_xu * @date 11. März 2012 * @return * / public static String getday () {try {return string.valueof (cale.get (calendar.day_of_month)); } catch (Ausnahme e) {logger.debug ("dateUtil.getday ():" + e.getMessage ()); zurückkehren ""; }} / ** * Vergleich der Anzahl der Tage zwischen zwei Daten * @author dylan_xu * @date März 2012 * @param Date1 * @param Date2 * @return * / public static int getMargin (String Datum1, String Datum2) {int Margin; try {parseposition pos = new Parseposition (0); Parseposition POS1 = NEUes Analyse (0); Datum dt1 = SDF_DATE_FORMAT.PARSE (DATE1, POS); Datum dt2 = SDF_DATE_FORMAT.PARSE (DATE2, POS1); long l = dt1.getTime () - dt2.getTime (); margin = (int) (l / (24 * 60 * 60 * 1000)); Return Marge; } catch (Ausnahme e) {logger.debug ("dateUtil.getmargin ():" + e.toString ()); Rückkehr 0; }} / ** * Vergleich der Anzahl der Tage, an denen sich die beiden Daten unterscheiden. try {parseposition pos = new Parseposition (0); Parseposition POS1 = NEUes Analyse (0); Datum dt1 = SDF_DATETIME_FORMAT.PARSE (DATE1, POS); Datum dt2 = SDF_DATETIME_FORMAT.PARSE (DATE2, POS1); long l = dt1.getTime () - dt2.getTime (); Margin = (l / (24 * 60 * 60 * 1000,00)); Return Marge; } catch (Ausnahme e) {logger.debug ("dateUtil.getmargin ():" + e.toString ()); Rückkehr 0; }} / ** * Vergleich der Anzahl der Monate zwischen den beiden Daten * @author dylan_xu * @date März 2012 * @param Date1 * @param Date2 * @return * / public static int getMonthmargin (String Datum1, String Datum2) {int margin; try {margin = (integer.parseInt (Datum2.Substring (0, 4)) - Integer.ParseInt (Datum1.Substring (0, 4)) * 12; Margin += (Integer.ParseInt (Datum2.Substring (4, 7) .ReplaceAll ("-0", "-")-Integer Return Marge; } catch (Ausnahme e) {logger.debug ("dateUtil.getmargin ():" + e.toString ()); Rückkehr 0; }} / ** * Geben Sie das Datum nach x Day Date * @Author Dylan_xu * @date März 2012 * @param Datum * @param i * @return * / public static String addday (String -Datum, int i) {try {gregoriangalendar gcal = new gregoriancalendar (intete.parseint () (Intetar () (Inteteger.ParseInt () (Intetar) (Inteteger.ParseInt () (Inteteger () (Inteteger.ParseNt) (Inteteger (inteteger.Parse) () (Integer.Parse Intiert (intiertar) (inteteger. Integer.ParseInt (Datum.Substring (5, 7)) - 1, Integer.ParseInt (Datum.Substring (8, 10))); gcal.add (Gregoriancalendar.date, i); return sdf_date_format.format (gcal.getTime ()); } catch (Ausnahme e) {logger.debug ("dateUtil.addday ():" + e.toString ()); return getDate (); } } /** * Return the date after the date plus X months* @author dylan_xu * @date Mar 11, 2012 * @param date * @param i * @return */ public static String addMonth(String date, int i) { try { GregorianCalendar gCal = new GregorianCalendar( Integer.parseInt(date.substring(0, 4)), Integer.ParseInt (Datum.Substring (5, 7)) - 1, Integer.ParseInt (Datum.Substring (8, 10))); gcal.add (Gregoriancalendar.month, i); return sdf_date_format.format (gcal.getTime ()); } catch (Ausnahme e) {logger.debug ("dateUtil.addmonth ():" + e.toString ()); return getDate (); }} / ** * Geben Sie das Datum nach dem Datum plus x Jahre zurück * @Author Dylan_xu * @date März 2012 * @param Datum * @param i * @return * / public static String addyear (String -Datum, int i) {try {gregoriancalendar gcal = new gregorandar (intiere.parseInt (substranding Integer.ParseInt (Datum.Substring (5, 7)) - 1, Integer.ParseInt (Datum.Substring (8, 10))); gcal.add (Gregoriancalendar.year, i); return sdf_date_format.format (gcal.getTime ()); } catch (Ausnahme e) {logger.debug ("dateUtil.addyear ():" + e.toString ()); zurückkehren ""; }} / ** * Geben Sie den maximalen Tag eines bestimmten Monats in einem bestimmten Jahr zurück. try {if (Imonth == 1 || Image == 3 || Image == 5 || Image == 7 || Image == 8 || Image == 10 || Image == 12) {Tag = 31; } else if (Imonth == 4 || Image == 6 || Image == 9 || Image == 11) {Tag = 30; } else if ((0 == (iyear % 4)) && (0! = (iyear % 100)) || (0 == (iyear % 400))) {Tag = 29; } else {Tag = 28; } Rückkehrtag; } catch (Ausnahme e) {logger.debug ("dateUtil.getMonthDay ():" + e.toString ()); Rückkehr 1; }} / ** * Formatdatum * @author dylan_xu * @date 11. März 2012 * @param orgdate * @param type * @param span * @return * / @SuppressWarnings ("static-access") public String roldate (String orgdate, int type, int span) {try {string temp = "; int iyear, Bild, 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); } Bild--; if (Imonth <0 || Bild> 11) {image = 0; } iday = integer.parseInt (temp); if (tag <1 || iday> 31) iday = 1; Kalender orgcale = calendar.getInstance (); orgcale.set (iyear, Bild, iday); temp = this.rolldate (Orgcale, Typ, Span); Temperatur zurückgeben; } catch (Ausnahme e) {return ""; }} public static String roldate (Kalender, int type, int span) {try {string temp = ""; Kalenderrolcale; rolcale = cal; rolcale.add (Typ, Span); temp = sdf_date_format.format (rolcale.getTime ()); Temperatur zurückgeben; } catch (Ausnahme e) {return ""; }} / ** * Zurück das Standarddatum-Format * @Author Dylan_xu * @date 11. März 2012 * @return * / public static synchronisierte String getDatePattern () {defaultDatePattern = "Yyyyy-Mm-Dd"; Rückgabe von StandardDatePattern; } / ** * Ersetzen Sie das angegebene Datum in eine Zeichenfolge im Standardformat und Ausgabe, wie z. String returnValue = ""; if (adate! = null) {df = new SimpledateFormat (getDatePattern ()); returnValue = df.Format (adate); } return (returnValue); } / ** * Erhalten Sie die Zeitzeichenfolge für das angegebene Datum. Das Format ist das aktuelle Standard -Zeitformat * @Author Dylan_xu * @date März 2012 * @param thetime * @return * / public static String getTimenow (Datum thetime) {return getDatetime (TimePattern, thetime); } / ** * Holen Sie sich das Kalender -Kalenderobjekt für die aktuelle Zeit * @Author Dylan_xu * @date 11. März 2012 * @return * @throws ParseException * / public calendar getToday () löscht ParseException {Datum heute = Neues Datum (); SimpleDateFormat df = new SimpledateFormat (getDatePattern ()); String TodayAssstring = df.format (heute); Kalender Cal = New Gregoriancalendar (); Cal.Settime (convertStringtodat (heute assstring)); return Cal; } / ** * Konvertieren Sie die Datumsklasse in ein Zeichenfolgenformular im angegebenen Format * @Author Dylan_xu * @date März 2012 * @param amask * @param adate * @return * / public static Final String getDatetime (String Amask, Datum Addate) {simpledateFormat df = null; String returnValue = ""; if (adate == null) {logger.Error ("adate is null!"); } else {df = new SimpledateFormat (Amask); returnValue = df.Format (adate); } return (returnValue); } / ** * Konvertieren Sie das angegebene Datum in das Zeichenfolgeformat im Standardformat * @Author Dylan_xu * @date 11. März 2012 * @param adate * @return * / public static Final String convertDateToString (Datum Adatate) {return getDatetime (getDatePattern (), adate); } / ** * Konvertieren Sie die Datumszeichenfolge in den Datumstyp im angegebenen Format * @Author Dylan_xu * @date März 2012 * @param amask Das angegebene Datumsformat wie: yyyy-mm-dd * @param Strdate Das Datum der Datumsstring, die konvertiert werden soll * @return * @whrows parseexception * / öffentliches statisches statisches statisches stolzes statisches statisches statisches statisches stolzes statisches stolzes statisches statisches statisches statisches statisches statisches statisches statisches statisches statisches statisches statates date convertstringtodat (strack) stroddata, stroddata, öffentlich) strates-static static static static static static. ParseException {SimpledateFormat df = null; Datum Datum = null; df = new SimpledateFormat (Amask); if (logger.isdebugenabled ()) {logger.debug ("Konvertieren" + strdate + "'bis mit Maske" " + Amask +"' "); } try {date = df.parse (strdate); } catch (parseException pe) {logger.Error ("ParseException:" + pe); pe werfen; } return (Datum); } / ** * DATUM -STRING CONVERT DATUM TEILT DATUM IM DEFAULT -Format * @Author Dylan_xu * @date März 2012 * @param strdate * @return * @throw ParseException * / public static Date convertstringTodate (String strdate) Auslöscht ParseException {Date adatate = null; try {if (logger.isdebugenabled ()) {logger.debug ("Konvertieren mit Muster:" + getDatePattern ()); } adate = convertStringtodat (getDatePattern (), strdate); } catch (ParseException pe) {logger.Error ("konnte nicht konvertieren" + strdate + "'in ein Datum, die Ausnahme werfen"); Neue ParseException (pe.getMessage (), pe.getEroroffset ()) werfen; } Rückgabe adate; } / ** * Gibt eine Datumszeichenfolge von Java -einfachen Typen zurück * @author dylan_xu * @date 11. März 2012 * @return * / public static String getImpledateFormat () {SimpleedateFormat Formatter = new SimpledateFormat (); String ndatetime = formatter.format (neues Datum ()); kehren ndatetime zurück; } /** * Comparison of the date in the specified string format with the current time* @author DYLAN * @date Feb 17, 2012 * @param strDate The time required to compare* @return * <p> * int code * <ul> * <li>-1 Current time<Compare time</li> * <li> 0 Current time=Compare time</li> * <li>>=1Current time> Compare time</li> * </ul> * </p> */public static int vergleichEcurTime (String strdate) {if (stringutils.isblank (strDate)) {return -1; } Date curtime = cale.getTime (); String strcurtime = null; try {strcurtime = sdf_datetime_format.format (curtime); } catch (Ausnahme e) {if (logger.isdebugenabled ()) {logger.debug ("[konnte nicht formatieren" " + strdate +" 'zu einem Datum, Ausnahme werfen: " + e.getLocalizedMessage () +"] "); }} if (stringutils.isnotblank (strcurtime)) {return Strcurtime.comPareto (strDate); } return -1; } / ** * Mindestzeit zum Abfragedatum * * @param Zieltyp Datum * @param Conversion Parameter Datum * @return * / @SuppressWarnings ("Abschaltung") öffentliches statisches Datum AddStartTime (Datum Param) {Datum = Param; try {date.sethoors (0); Datum.SetMinutes (0); Datum.SetSeconds (0); Rückgabedatum; } catch (Ausnahme ex) {Rückgabedatum; }} / ** * maximale Zeit hinzufügen, um Datum abzufragen * * @param Zieltyp Datum * @param Conversion Parameter Datum * @return * / @Suppresswarnings ("Abschaltung") öffentliches statisches Datum AddendTime (Datum Param) {Datum = Param; try {date.sethoors (23); Datum.SetMinutes (59); Datum.SetSeconds (0); Rückgabedatum; } catch (Ausnahme ex) {Rückgabedatum; }} / *** Geben Sie die Anzahl der Tage im aktuellen Jahr des Systems zurück. 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 Jahr = Datum.Getyear () + 1900; if (Jahr % 4 == 0 && Jahr % 100! = 0 || Jahr % 400 == 0) {Return Day [1] [Monat] + ""; } else {Return Day [0] [Monat] + ""; } } /** * 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 (Jahr % 4 == 0 && Jahr % 100! = 0 || Jahr % 400 == 0) {Return Day [1] [Monat] + ""; } else {Return Day [0] [Monat] + ""; }} / ** * Beurteilen Sie, ob es sich um ein normales Jahr oder ein Schaltjahr handelt. } else {return false; }} / ** * Holen Sie sich den Tagesstempel der aktuellen Zeit * @Author Dylan_xu * @date 11. März 2012 * @return * / @SuppressWarnings ("Abschaltung") public static String getTimestamp () {Datum Date = cale.getime (); String timestamp = "" + (Datum.Getyear () + 1900) + Date.getMonth () + Date.getDate () + Date.getminutes () + Date.getSeconds () + Date.getTime (); Return Timestamp; } / ** * Holen Sie sich den Tagesstempel der angegebenen Zeit * * @return * / @Suppresswarnings ("Abschaltung") öffentlich statische String -String -Gettimestamp (Datum Datum) {String timestamp = "" + (Date.Getyear ()) + 1900) + Date.GetMonth () + Date.GetDate () + DateMin.; Return Timestamp; } public static void main (String [] args) {System.out.println (getyear () + "|" + getMonth () + "|" + getDate ()); }}Das Obige dreht sich alles um diesen Artikel, ich hoffe, es wird für das Lernen aller hilfreich sein.