구현 코드 1 :
import java.text.simpledateformat; import java.util.calendar; import java.util.date; public class dateTeTestutil {public static void main (String [] args)은 예외 {simpledateformat sdf = new SimpledateFormat ( "yyyymmdd"); String str = "20110823"; 날짜 dt = sdf.parse (str); Calendar RightNow = Calendar.getInstance (); RightNow.settime (dt); rightnow.add (calendar.year, -1); // 날짜 마이너스 1 년 rightnow.add (calendar.month, 3); // 날짜 + 3 개월 + rightnow.add (calendar.day_of_year, 10); // 날짜 + 10 일 날짜 dt1 = rightnow.gettime (); 문자열 구속 = sdf.format (dt1); System.out.println (구속); }}참고 : 캘린더 객체의 추가 방법에서 두 번째 매개 변수는 "add"를 의미하는 양수이고 "뺄셈"을 의미하는 음수입니다.
코드 2 : Java 날짜는 일일을 추가하고 빼냅니다.
테스트 클래스 코드 :
import java.text.simpledateformat; import java.util.date; public class dateTest {public static void main (String [] arg) {date now = new Date (); AddandSubtractDaysBygetTime (현재 -5); AddandSubtractDaysBygetTime (현재, 5); addandsubtractdaysbycalendar (현재, -5); AddandSubtractDaysByCalendar (현재, 5); } 공개 정적 날짜 addandSubtractDaysByGetTime (날짜 datetime/*보류 날짜*/, int n/*추가 및 뺄셈 일*/) {// 날짜 형식 simpledateformat df = new SimpledateFormat ( "yyyy-mm-dd"); simpledateformat dd = 새로운 simpledateformat ( "yyyy-mm-dd hh : mm : ss"); System.out.println (df.format (새 날짜 (datetime.gettime () + n * 24 * 60 * 60 * 1000l))); //system.out.println(dd.format(new date (datetime.gettime () + n * 24 * 60 * 60 * 1000l))); // 여기에서 긴 유형으로 변환해야합니다. 그렇지 않으면 N이 25를 초과 할 때 범위 오버 플로우가 발생하여 원하는 날짜 값을 얻을 수 없도록 새 날짜를 반환 할 수 없습니다 (dateTime.getTime.getTime () + n * 24 * 60 * 60 * 1000L); } 공개 정적 날짜 addandSubtractDaysByCalendar (날짜 dateTime/*보류 날짜*/, int n/*추가 및 뺄셈 일*/) {// 날짜 형식 simpledateformat df = new SimpledateFormat ( "yyyy-mm-dd"); simpledateformat dd = 새로운 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 (); }} 실행 결과 :
2014-10-06
2014-10-16
2014-10-06
2014-10-16
코드 3 :
온라인으로 정보를 확인하고 요약 한 날짜 클래스에 대한 도구 클래스를 추가하십시오.
package com.data.utils; import java.text.simpledateformat; import java.util.calendar; import java.util.date; public class dateformat { / *** 수는 날짜의 날짜 감소* / public string dateminusyear (string str) {simpledateformat sdf = 새로운 Simpleateformm ( "); 날짜 dt = sdf.parse (str); Calendar RightNow = Calendar.getInstance (); RightNow.settime (dt); rightnow.add (calendar.year, -1); // 날짜 마이너스 1 년 날짜 dt1 = rightnow.gettime (); 문자열 구속 = sdf.format (dt1); 반환 구속; } / *** 날짜에 몇 년을 추가 해야하는지* / public static string dateaddyear (String Str) 예외 {simpledateformat sdf = new simpledateformat ( "yyyymm"); 날짜 dt = sdf.parse (str); Calendar RightNow = Calendar.getInstance (); RightNow.settime (dt); rightnow.add (calendar.year, 1); // 날짜 + 1 년 날짜 dt1 = rightnow.gettime (); 문자열 구속 = sdf.format (dt1); 반환 구속; } / *** 날짜가 몇 개월 줄어드* / public static string dateminusmonth (String str)는 예외 {simpledateformat sdf = new simpledateformat ( "yyyymm"); 날짜 dt = sdf.parse (str); // 문자열 calendar rightnow = calendar.getInstance ()를 생성합니다. rightnow.settime (dt); // 주어진 날짜를 사용 하여이 캘린더의 시간을 설정하십시오. rightnow.add (calendar.month, -1); // 날짜 마이너스 1 개월 날짜 dt1 = rightnow.gettime (); // 캘린더 시간 값을 나타내는 날짜 개체를 반환합니다. String rest = sdf.format (dt1); // 주어진 날짜를 날짜/시간 문자열로 서식하고 주어진 StringBuffer에 결과를 추가하십시오. 반환 구속; } / ** * 날짜는 몇 개월을 추가합니까 * / public static string dateaddmonth (String Str)는 예외 {simpledateformat sdf = new simpledateformat ( "yyyymm"); 날짜 dt = sdf.parse (str); Calendar RightNow = Calendar.getInstance (); RightNow.settime (dt); rightnow.add (calendar.month, 1); // 날짜 3 개월 추가 // rightnow.add (calendar.day_of_year, 10); // 날짜 + 10 일 dt1 = rightnow.gettime (); 문자열 구속 = sdf.format (dt1); 반환 구속; } / ** * 현재 연도 및 달의 첫 달에 str을 얻으십시오 * @param str * 201505 * @return 201501 * @throws Exception * / public static string dateonemonth (string str) {str = str.substring (0, str.length () -2); str = str + "01"; Return str; } /*** 1 월부터 선택된 달의 달의 수를 계산하십시오. * @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); 반환 i -j + 1; } / ** * 밀리 초에서 정확한 두 번 사이의 시차를 얻습니다. * @param st * @return * / public static string timedifference (긴 시작, 긴 끝) {long 사이의 = 종료 - 시작; 긴 날 = / (24 * 60 * 60 * 1000); 긴 시간 = ( / (60 * 60 * 1000) -Day * 24); long min = (( / (60 * 1000)) -Day * 24 * 60 -Hour * 60); long s = ( / 1000 -day * 24 * 60 * 60 -Hour * 60 -Min * 60); 긴 ms = ( -day * 24 * 60 * 60 * 1000 -hour * 60 * 60 * 60 * 1000 -min * 60 * 1000 -s * 1000); 문자열 timedifference = day + "day" + hour "hour" + min + "minute" + s + "seconds" + ms + "milliseconds"; 반환 시간 확률; }} / ** * 24 시간, 일주일 및 1 개월의 시작 시간을 얻습니다 * * @param timeinterval * : day_time_interval week_time_interval month_time_interval * @return "yyyy-mm-dd hh : mm : ss" * / public static string getstarttime (int timeinterval) {calendar calendar. simpledateformat sdf = new simpledateformat ( "yyyy-mm-dd hh : mm : ss"); if (day_time_interval == TimeInterval) {// 24 시간 시작 시간을 가져옵니다. cal.set (calendar.hour_of_day, 0); cal.set (calendar.minute, 0); cal.set (calendar.second, 0); 문자열 startTime = sdf.format (cal.gettime ()); 리턴 시작 시간; } else if (week_time_interval == TimeInterval) {int weekday = cal.get (calendar.day_of_week) -1; cal.add (calendar.date, -weekday); cal.set (calendar.hour_of_day, 0); cal.set (calendar.minute, 0); cal.set (calendar.second, 0); 문자열 startTime = sdf.format (cal.gettime ()); 리턴 시작 시간; } else if (month_time_interval == TimeInterval) {int dayofmonthmin = cal.getActualMinimum (calendar.day_of_month); // c.add (calendar.date, -dayofmonth); cal.set (calendar.date, dayofmonthmin); cal.set (calendar.hour_of_day, 0); cal.set (calendar.minute, 0); cal.set (calendar.second, 0); 문자열 startTime = sdf.format (cal.gettime ()); 리턴 시작 시간; } return null; } / ** * 24 시간, 일주일 및 1 개월의 종료 시간을 얻습니다 * * * @param timeinterval * : day_time_interval thek_time_interval month_time_interval * @return "yyyy-mm-dd hh : mm : ss" * / public static string getendtime (int timeinterval) {Calendar 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); 긴 날짜 = cal.getTimeInmillis (); 문자열 endtime = sdf.format (새 날짜 (날짜)); 반환 종료 시간; } else if (week_time_interval == TimeInterval) {int weekday = cal.get (calendar.day_of_week) -1; cal.add (calendar.date, -weekday); cal.add (calendar.date, 6); cal.set (calendar.hour_of_day, 23); Cal.set (12, 59); Cal.set (13, 59); 긴 날짜 = cal.getTimeInmillis (); 문자열 endtime = sdf.format (새 날짜 (날짜)); 반환 종료 시간; } else if (month_time_interval == TimeInterVal) {int dayofmonthmax = cal.getActualMaximum (calendar.day_of_month); cal.set (calendar.date, dayofmonthmax); cal.set (calendar.hour_of_day, 23); cal.set (calendar.minute, 59); cal.set (calendar.second, 59); 문자열 endtime = sdf.format (cal.gettime ()); 반환 종료 시간; } return null; } /*** DateSt가 시작과 끝 사이에 있는지 여부를 결정합니다. 시작과 끝은 모두 null yyyymmddhhmmss 또는 yyyymmdd 형식 * * @author you.xu * @date 2015 년 8 월 19 일 오후 3:11:46 pm * @param datest * @param start * @param end * @return */ public static bolean checkdateval (문자열 시작, 문자열) {boolean isdatergend) 날짜 날짜 = null; 날짜 startDate = null; 날짜 종료 = null; simpledateformat sdf = null; // 날짜 형식 if (14 == datest.length ()) {sdf = new SimpledateFormat ( "yyymmddhhmmss"); } else if (8 == dateSt.length ()) {sdf = new simpledateformat ( "yyyymmdd"); } 그렇지 않으면 거짓을 반환합니다. 시도 {// 판사 날짜 형식을 변경합니다. 날짜 = sdf.parse (dateSt); } catch (parseexception e) {log.error (e, e); } if ((start == null) && (end! = null)) {try {enddate = sdf.parse (end); } catch (parseexception ex1) {log.error (예 : 예 : 예 : Ex1); } if ((date! = null) && (endDate! = null)) // {if (date.compareto (endDate) <= 0) isdateright = true; }} else if ((start! = null) && (end == null)) {try {startDate = sdf.parse (start); } catch (parseexception ex1) {log.error (예 : 예 : 예 : Ex1); } if ((date! = null) && (startDate! = null)) {if (date.compareto (startDate)> = 0) isdateright = true; }} else if ((start! = null) && (end! = null)) {try {startDate = sdf.parse (start); enddate = sdf.parse (끝); } 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; } / ** * DateStres가 시작과 끝 사이에 있는지 여부를 결정하기 위해 시작과 끝이 모두 긴 형식으로 될 수 있습니다 * @author you.xu * @date 2015 년 8 월 19 일 오후 3:12:35 PM * @param datest * @param start * @param end * @return * / public static bolean checkDatev (String DateStr, String, String) {boolean isdatergheath isdatergheath); 긴 날짜 = -1; 길고 다. -1; 긴 토데이트 = -1; 날짜 = java.lang.long.parselong (datest); if ((start == null) && (end == null)) {isdateright = true; } else if ((start == null) && (end! = null)) {try {todate = java.lang.long.parselong (end); } catch (numberformatexception nfe) {log.error (nfe, nfe); } if (date <= todate) {isdateright = true; }} else if ((start! = null) && (end == null)) {try {fromdate = java.lang.long.parselong (start); } catch (numberformatexception nfe) {log.error (nfe, nfe); } if (date> = fromDate) {isdateright = true; }} else if ((start! = null) && (end! = null)) {try {todate = java.lang.long.parselong (end); Fromdate = java.lang.long.parselong (시작); } catch (numberformatexception nfe) {log.error (nfe, nfe); } if ((date <= todate) && (날짜> = fromDate)) {isdateright = true; }} return isdateright; }이것들은 지금까지 사용되며 언제든지 추가 할 수 있습니다. 간단하고 편리한 시간 도구가 있습니다. 나는 당신과 함께 배우고 싶습니다. 그리고 나는 그 의견에서 그들을 지적 할 것입니다. 감사해요! ! !