이 기사는 주로 날짜 처리를 위해 두 부분으로 나뉩니다. 다음은 자세한 소개입니다.
1 부 : 날짜 처리의 기본
날짜 클래스 <br /> 함수 : 주요 함수는 현재 시간을 얻고 날짜를 표준 형식으로 변환하는 것입니다.
날짜 날짜 = 새 날짜 (); simpledateformat sdf = new simpledateformat ( "yyyy-mm-dd hh : mm : ss"); String str = sdf.format (날짜); System.out.println ( "2015-10-16 14:59:52");
문자열을 날짜 유형으로 변환합니다
문자열 day = "2014-6-5 10:30:30"; simpledateformat d2 = new simpledateformat ( "yyyy-mm-dd hh : mm : ss"); 날짜 날짜 2 = d2.parse (day); system.out.println ( "thu 6 월 10:30:30 cst 2014");
캘린더 클래스 응용 프로그램
java.util.calendar 클래스는 추상 클래스입니다. getInstance () 정적 메소드를 호출하여 캘린더 객체를 얻을 수 있습니다. 이 객체는 현재 날짜와 시간, 즉 기본적으로 현재 시간을 나타냅니다.
calendar c = calendar.getInstance (); int 년 = c.get (calender.year); int month = c.get (calender.month) +1; // 달을 얻습니다.
2 개월을 다른 시간과 비교하십시오
simpledateformat 형식 = 새로운 simpledateformat ( "yyyy-mm-dd hh : mm : ss"); datetime d1 = new datetime (format.parse ( "2016-10-31 00:00:00"); dateTime d2 = new DateTime ( "2015-1-31 00:00:00 ")); System.out.println (math.abs (Months.monthsbetween (d1, d2) .getmonths ());
2 부 : 날짜 처리 도구 클래스
패키지 com.analysys.website.control; 가져 오기 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; /** * 날짜 처리 도구 클래스 * @Author dylan_xu * @date 2012 년 3 월 11 일 * @Modified * @Modified 날짜 * @Since JDK1.6 * @see com.util.dateutil */public class dateUtil {// ~ 정적 필드/이니셜 라이저 // ========================================= Private Static Logger Logger = logger.getLogger (dateUtil.class); 개인 정적 문자열 defaultDatePattern = null; 비공개 정적 문자열 timepattern = "hh : mm"; 개인 정적 캘린더 Cale = Calendar.getInstance (); 공개 정적 최종 문자열 ts_format = dateUtil.getDatePattern () + "hh : mm : ss.s"; / ** 날짜 형식 YYYY-MM 문자열 상수*/ 개인 정적 최종 문자열 Month_Format = "yyyy-mm"; / ** 날짜 형식 YYYY-MM-DD 문자열 상수*/ 개인 정적 최종 문자열 date_format = "yyyy-mm-dd"; / ** 날짜 형식 HH : MM : SS 문자열 상수*/ 개인 정적 최종 문자열 Hour_Format = "HH : MM : SS"; / ** 날짜 형식 YYYY-MM-DD HH : MM : SS 문자열 상수*/ 개인 정적 최종 문자열 DATETIME_FORMAT = "YYYY-MM-DD HH : MM : SS"; / ** 하루의 시작, 분 및 두 번째 문자열 상수 00:00:00*/ 개인 정적 최종 문자열 day_begin_string_hhmmss = "00:00:00"; / ** 하루의 시작, 분 및 두 번째 문자열 상수 23:59:59*/ public static final String day_end_string_hhmmss = "23:59:59"; 개인 정적 단순한 simpledateformat sdf_date_format = new SimpledateFormat (date_format); 개인 정적 단순한 simpledateformat sdf_hour_format = new SimpledateFormat (Hour_format); 개인 정적 단순한 simpledateformat sdf_datetime_format = new SimpledateFormat (dateTime_format); // ~ 방법 // =================================================================================================== / ** * 서버의 현재 날짜와 시간을 가져오고, 형식의 날짜 문자열 형식으로 반환합니다. } catch (예외 e) {logger.debug ( "dateUtil.getDateTime () :" + e.getMessage ()); 반품 ""; }} / ** * 서버의 현재 날짜를 가져오고, 형식의 날짜 문자열 형식으로 반환합니다. } catch (예외 e) {logger.debug ( "dateUtil.getDate () :" + e.getMessage ()); 반품 ""; }} / ** * 서버의 현재 시간을 가져 와서 형식의 날짜 문자열 형식으로 반환합니다. try {temp += sdf_hour_format.format (cale.gettime ()); 반환 온도; } catch (예외 e) {logger.debug ( "dateUtil.gettime () :" + e.getMessage ()); 반품 ""; }} / ** * 통계 동안 시작 날짜의 기본값 * @author dylan_xu * @date 2012 * @return * / public static string getStartDate () {retry {return getyear () + "--01-01"; } catch (예외 e) {logger.debug ( "dateUtil.getStartDate () :" + e.getMessage ()); 반품 ""; }} / ** * 통계 동안 종료 날짜의 기본값 * @Author dylan_xu * @Date 2012 * @return * / public static string getEndDate () {try {return getDate (); } catch (예외 e) {logger.debug ( "dateUtil.getendDate () :" + e.getMessage ()); 반품 ""; }} / ** * 서버의 현재 날짜 연도 * @author dylan_xu * @date 2012 * @return * / public static string getyear () {retry {return.valueof (cale.get (calendar.year)); } catch (예외 e) {logger.debug ( "dateUtil.getyear () :" + e.getMessage ()); 반품 ""; }} / ** * 서버의 현재 날짜를 얻으십시오 * @author dylan_xu * @date 2012 * @return * / public static string getmonth () {try {java.text.decimalformat df = new java.text.decimalformat (); df.applypattern ( "00; 00"); df.format을 반환합니다 ((cale.get (calendar.month) + 1)); } catch (예외 e) {logger.debug ( "dateUtil.getMonth () :" + e.getMessage ()); 반품 ""; }} / ** * 서버의 현재 달의 일수를 얻습니다. * @author dylan_xu * @date 2012 년 3 월 11 일 * @return * / public static string getday () {retry {return.valueof (cale.get (calendar.day_of_month)); } catch (예외 e) {logger.debug ( "dateUtil.getDay () :" + e.getMessage ()); 반품 ""; }} / ** * 두 날짜 사이의 일수 비교 * @author dylan_xu * @date 2012 * @param date1 * @param date2 * @return * / public static int getmargin (문자열 날짜 1, 문자열 날짜 2) {int margin; try {parseposition pos = new parseposition (0); Parseposition POS1 = 새로운 구문 분석 (0); 날짜 dt1 = sdf_date_format.parse (date1, pos); 날짜 dt2 = sdf_date_format.parse (date2, pos1); long l = dt1.gettime () -dt2.gettime (); 마진 = (int) (l / (24 * 60 * 60 * 1000)); 리턴 마진; } catch (예외 e) {logger.debug ( "dateUtil.getMargin () :" + e.toString ()); 반환 0; }} / ** * 두 날짜가 다른 날의 수치 * @author dylan_xu * @date 2012 년 3 월 11 일 * @param date1 * @param date2 * @return * / public static double getDoublemargin (문자열 날짜 1, 문자열 날짜 2) {double margin; try {parseposition pos = new parseposition (0); Parseposition POS1 = 새로운 구문 분석 (0); 날짜 dt1 = sdf_dateTime_format.parse (date1, pos); 날짜 dt2 = sdf_dateTime_format.parse (date2, pos1); long l = dt1.gettime () -dt2.gettime (); 여백 = (l / (24 * 60 * 60 * 1000.00)); 리턴 마진; } catch (예외 e) {logger.debug ( "dateUtil.getMargin () :" + e.toString ()); 반환 0; }} / ** * 두 날짜 사이의 달 수의 비교 * @author dylan_xu * @date 2012 * @param date1 * @param date2 * @return * / public static int getmonthmargin (문자열 날짜 1, 문자열 날짜 2) {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", "-"))); 리턴 마진; } catch (예외 e) {logger.debug ( "dateUtil.getMargin () :" + e.toString ()); 반환 0; }} / ** * X 날짜 이후 날짜를 반환 * @author dylan_xu * @date 2012 년 3 월 11 일 * @param 날짜 * @param i * @return * / public static string addday (문자열 날짜, int i) {gregoriancalendar gcal = new GregorianCalendar (integor.parse.parse.spstring (0, 4)). integer.parseint (date.substring (5, 7)) -1, integer.parseint (date.substring (8, 10))); gcal.add (gregoriancalendar.date, i); 반환 sdf_date_format.format (gcal.gettime ()); } catch (예외 e) {logger.debug ( "dateUtil.addday () :" + e.toString ()); return getDate (); }} / ** * 날짜 + x 개월 후 날짜를 반환하십시오 * @author dylan_xu * @date 2012 * @param 날짜 * @param i * @return * / public static string addmonth (문자열 날짜, int i) {gregoriancalendar gcal = new gregoriancalendar (integoriancalendar (integoriancalendar) integer.parseint (date.substring (5, 7)) -1, integer.parseint (date.substring (8, 10))); gcal.add (gregoriancalendar.month, i); 반환 sdf_date_format.format (gcal.gettime ()); } catch (예외 e) {logger.debug ( "dateUtil.addmonth () :" + e.toString ()); return getDate (); }} / ** * 날짜 + x 년 후 날짜를 반환 * @author dylan_xu * @date 2012 년 3 월 11 일 * @param 날짜 * @param i * @return * / public static string addyear (문자열 날짜, int i) {gregoriancalendar gcal = new GregorianCalendar (integoriancalendar (integoriancalendar) integer.parseint (date.substring (5, 7)) -1, integer.parseint (date.substring (8, 10))); gcal.add (gregoriancalendar.year, i); 반환 sdf_date_format.format (gcal.gettime ()); } catch (예외 e) {logger.debug ( "dateUtil.addyear () :" + e.toString ()); 반품 ""; }} / ** * 특정 연도에 특정 달의 최대 날을 반환 * @author dylan_xu * @date 2012 * @param year * @param month * / public static int getmaxday (int iyear, int image) {int day = 0; try {if (iMonth == 1 || image == 3 || image = 5 || image == 7 || image == 8 || 이미지 == 10 || 이미지 == 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; } 반환 일; } catch (예외 e) {logger.debug ( "dateUtil.getMonthday () :" + e.toString ()); 반환 1; }} / ** * 형식 날짜 * @author dylan_xu * @Date 2012 년 3 월 11 일 * @param orgdate * @param type * @param span * @return * / @suppresswarnings ( "static-access") public String Rolldate (문자열 orgdate, int type, int span) {strem temp = ""; 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); } 이미지-; if (imonth <0 || image> 11) {image = 0; } iday = integer.parseint (temp); if (day <1 || iday> 31) iday = 1; 캘린더 orgcale = calendar.getInstance (); orgcale.set (iyear, image, iday); temp = this.rolldate (orgcale, type, span); 반환 온도; } catch (예외 e) {return ""; }} public static string rolldate (Calendar Cal, int type, int span) {try {string temp = ""; 달력 롤 컴일; Rolcale = cal; rolcale.add (유형, 스팬); temp = sdf_date_format.format (rolcale.gettime ()); 반환 온도; } catch (예외 e) {return ""; }} / ** * 기본 날짜 형식을 반환 * @author dylan_xu * @date 2012 * @return * / public static synchronized string getDatePattern () {defaultDatePattern = "yyyy-mm-dd"; return defaultDatePattern; } / ** * 지정된 날짜를 기본 형식 및 출력으로 문자열로 대체합니다. 문자열 returnValue = ""; if (adate! = null) {df = new SimpledateFormat (getDatePattern ()); returnValue = df.format (adate); } return (returnValue); } / ** * 주어진 날짜에 대한 시간 문자열을 가져 오십시오. 형식은 현재 기본 시간 형식입니다 * @Author dylan_xu * @Date 2012 * @Param thetime * @return * / public static gettimenow (날짜 time) {return getDateTime (TimePattern, Thetime); } / ** * 현재 시간 동안 캘린더 캘린더 객체를 가져옵니다 * @Author dylan_xu * @Date 2012 년 3 월 11 일 * @return * @throws parseException * / public 캘린더 getToday () parseexception {date = new Date (); simpledateformat df = new simpledateformat (getDatePattern ()); String TodayAsstring = df.format (오늘); Calendar Cal = New GregorianCalendar (); cal.settime (convertstringtodate (TodayAsstring)); 반환 cal; } / ** * 날짜 클래스를 지정된 형식으로 문자열 양식으로 변환 * @author dylan_xu * @date 2012 * @param amask * @param adate * @return * / public static final String getDateTime (String Amask, Date Adate) {simplededateformat df = null; 문자열 returnValue = ""; if (adate == null) {logger.error ( "adate is null!"); } else {df = new SimpledateFormat (amask); returnValue = df.format (adate); } return (returnValue); } / ** * 지정된 날짜를 기본 형식으로 문자열 양식으로 변환 * @author dylan_xu * @date 2012 * @param adate * @return * / public static final String (날짜 adate) {return getDateTime (getDatePattern (), adate); } / ** * 지정된 형식으로 날짜 문자열을 날짜 유형으로 변환 * @author dylan_xu * @date 2012 * @param amask : yyyy-mm-dd * @param strdate 날짜 문자열 * @return * @throws parseexception * / public strows attring toctort (stringtringtringtringtringtringtring to) parseexception {simpledateformat df = null; 날짜 날짜 = null; df = 새로운 simpledateformat (amask); if (logger.isdebugenabled ()) {logger.debug ( "변환 '" + strdate + "'마스크와 함께 현재까지 '" + amask + "'"); } try {date = df.parse (strdate); } catch (parseexception pe) {logger.error ( "parseexception :" + pe); PE를 던지십시오. } return (날짜); } / ** * 기본 형식에서 날짜 문자열을 날짜로 변환합니다. try {if (logger.isdebugenabled ()) {logger.debug ( "패턴으로 날짜 변환 :" + getDatePattern ()); } adate = convertStringTodate (getDatePattern (), strdate); } catch (parseException pe) {logger.error ( "" " + strdate +" '' '' ''날짜로, 예외를 던지지 않음 "); 새 parseexception (pe.getMessage (), pe.getErrorOffset ()); } 반환 adate; } / ** * Java Simple Type의 날짜 문자열을 반환 * @author dylan_xu * @date 2012 * @return * / public static string getSimpledateformat () {simplededateformat formatter = new SimpledateFormat (); 문자열 ndatetime = formatter.format (new date ()); ndateTime을 반환합니다. }/** * 현재 시간과 지정된 문자열 형식의 날짜 비교 * @Author Dylan * @Date 2012 년 2 월 17 일 * @param strdate 비교 * @return * <p> * int code * <ul> * <li> -1 현재 시간 <비교 시간 </li> * <li> 0 현재 시간 </li> * <li> * >> 1cent </li> * >> * </ p> */ public static int comparetocurtime (string strdate) {if (stringUtils.isblank (strdate)) {return -1; } date curtime = cale.gettime (); 문자열 strcurtime = null; try {strcurtime = sdf_dateTime_format.format (curtime); } catch (Exception e) {if (logger.isdebugenabled ()) {logger.debug ( "[[[[[[[[gregger. }} if (stringUtils.isnotblank (strcurtime)) {return strcurtime.compareto (strdate); } 반환 -1; } / ** * 쿼리 날짜에 최소 시간 추가 * * @param 대상 유형 날짜 * @param 변환 매개 변수 날짜 * @return * / @suppresswarnings ( "감가 상각") 공개 정적 날짜 AddStartTime (날짜 param) {날짜 날짜 = param; try {date.sethours (0); 날짜 .SetMinutes (0); 날짜 .setseconds (0); 반환 날짜; } catch (예외) {반환 날짜; }} / ** * 쿼리 날짜에 최대 시간 추가 * * @param 대상 유형 날짜 * @param 변환 매개 변수 날짜 * @return * / @suppresswarnings ( "감가 상각") 공개 정적 날짜 addendtime (날짜 param) {날짜 날짜 = param; try {date.sethours (23); 날짜. 세트 분기 (59); 날짜 .setseconds (0); 반환 날짜; } catch (예외) {반환 날짜; }} / *** 시스템의 현재 연도의 일수를 반환** @param month* @return 지정된 달의 총 일수* / @suppresswarnings ( "감가 상각") 공개 정적 문자열 getmonthlastday (int month) {date date = new 날짜 (); int [] [] day = {{{0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 31, 31, 30, 31, 30, 30, 31, 30, 31}}; int 년 = date.getyear () + 1900; if (년 % 4 == 0 && 년 % 100! = 0 || 년 % 400 == 0) {return day [1] [Month] + ""; } else {return day [0] [Month] + ""; }} / ** * 지정된 연도에 지정된 달의 일수를 반환 * * @param 연도 * @param month * @return 지정된 월 * / public static string getmonthlastday (int year, int month) {] [] day = {{{0, 30, 30, 28, 31, 30, 31, 31, 31, 31, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31, 30, 31}}}; if (년 % 4 == 0 && 년 % 100! = 0 || 년 % 400 == 0) {return day [1] [Month] + ""; } else {return day [0] [Month] + ""; }} / ** * 평범한 해인지 도약 여부를 판단하십시오 * @author dylan_xu * @date 2012 * @param year * @return * / public static boolean isleapyear (int 년) {if (Year % 4 == 0 && 년 % 100! = 0) || (년 % 400) == 0) } else {return false; }} / ** * 현재 시간의 날 스탬프를 가져옵니다 * @author dylan_xu * @date 2012 * @return * / @SuppressWarnings ( "Dequrecation") public static string getTimestamp () {date date = cale.gettime (); String timestamp = " + (date.getyear () + 1900) + date.getmonth () + date.getDate () + date.getMinutes () + date.getSeconds () + date.gettime (); 반환 타임 스탬프; } / ** * 지정된 시간의 날 스탬프를 가져옵니다 * * @return * / @suppresswarnings ( "감가 상각") public static string getTimestamp (date date) {String timestamp = " + (date.getyear ()) + 1900) + date.getmonth () + date.get.get.get.get.get.get.get.getminutes () + date.getminutes (); 반환 타임 스탬프; } public static void main (String [] args) {System.out.println (getyear () + "|" + getMonth () + "|" + getDate ()); }}위의 내용은이 기사에 관한 모든 것입니다. 모든 사람의 학습에 도움이되기를 바랍니다.