형식이 올바른 한 문자열을 직접 비교하면 몇 초 동안 동일합니다.
문자열 s1 = "2003-12-12 11:30:24"; 문자열 s2 = "2004-04-01 13:31:40"; int res = s1.compareto (s2);
날짜 차이를 찾으십시오
simpledateformat df = 새로운 simpledateformat ( "yyyy-mm-dd hh : mm : ss"); 날짜 시작 = df.parse ( "2004-01-02 11:30:24"); 날짜 종료 = df.parse ( "2004-03-26 13:31:40"); long mine = (end.gettime ()-begin.gettime ())/1000; // 1000으로 나누는 것입니다. int Hour =%(24*3600)/3600; int minute =%3600/60 사이; int Second =%60;
시간과 날짜 클래스는 종종 사용되므로 일반적으로 사용되는 날짜 방법과 속성은 모든 사람이 찾을 수 있도록 다음과 같이 요약됩니다.
1. 특정 달의 최대 일 수를 계산합니다.
캘린더 시간 = calendar.getInstance (); time.clear (); time.set (calendar.year, 연도); time.set (calendar.month, i-1); // 캘린더 객체는 1 월 0 일 int day = time.getActualMaximum (calendar.day_of_month)까지 기본적으로 기본값을받습니다.
참고 : 설정 방법을 사용하기 전에 먼저 지우는 것이 가장 좋습니다. 그렇지 않으면 많은 정보가 현재 시스템 시간에서 상속됩니다.
2. 달력 및 날짜의 변환
(1) 일정은 현재까지 변환되었습니다
Calendar Cal = Calendar.getInstance (); 날짜 = cal.gettime ();
(2) 날짜를 달력으로 변환합니다
날짜 = 새 날짜 (); Calendar Cal = Calendar.getInstance (); cal.settime (날짜);
3. 출력 날짜와 시간을 형식화하십시오
날짜 = 새 날짜 (); simpledateformat df = 새로운 simpledateformat ( "yyyy-mm-dd hh : mm : ss"); System.out.println (df. format (date));
4. 연도의 주를 계산하십시오
(1) 하루 중 일주일을 계산합니다.
Calendar Cal = Calendar.getInstance (); cal.set (calendar.year, 2006); cal.set (calendar.month, 9); cal.set (calendar.day_of_month, 3); int weekno = cal.get (calendar.week_of_year);
(2) 일주일이 무엇인지 계산하십시오
simpledateformat df = 새로운 simpledateformat ( "yyyy-mm-dd"); Calendar Cal = Calendar.getInstance (); cal.set (calendar.year, 2006); cal.set (calendar.week_of_year, 1); cal.set (calendar.day_of_week, calendar.monday); System.out.println (df.format (cal.gettime ());
산출:
2006-01-02
5. add () 및 roll ()의 사용
(1) add () 메소드
simpledateformat df = 새로운 simpledateformat ( "yyyy-mm-dd"); Calendar Cal = Calendar.getInstance (); cal.set (calendar.year, 2006); cal.set (calendar.month, 9); cal.set (calendar.day_of_month, 3); cal.add (calendar.date, -4); 날짜 = cal.gettime (); System.out.println (df. format (date)); cal.add (calendar.date, 4); 날짜 = cal.gettime (); System.out.println (df. format (date));
산출:
2006-08-30
2006-10-03
(2) 롤 방법
cal.set (calendar.year, 2006); cal.set (calendar.month, 9); cal.set (calendar.day_of_month, 3); cal.roll (calendar.date, -4); 날짜 = cal.gettime (); System.out.println (df. format (date)); Cal.Roll (Calendar.Date, 4); 날짜 = cal.gettime (); System.out.println (df. format (date));
산출:
2006-10-29
2006-10-03
이 달 내에 Roll () 메소드가 루프되고 Add () 메소드가 일반적으로 사용됨을 알 수 있습니다.
6. 두 임의의 시간 사이의 일 수를 계산합니다.
(1) 달력 객체로 전달
/*** // ** 두 번 사이의 일수를 계산* @param startday 시작 시간* @param endday 종료 시간* @return*/publendar startday, calendar endday) .. 각각 긴 sl = startday.getTimeInmillis (); long el = endday.gettimeinmillis (); long ei = el-sl; // milliseconds return (int) (ei/(1000*60*60*24))를 기준으로 간격 일을 계산합니다.
(2) 날짜 개체로 전달
/*** // ** 두 번* @param startday 시작 시간* @param endday end time* @return*/public int getintervaldays (날짜 시작, 날짜 종료일) ... sl = startday.gettime (); long el = endday.gettime (); long ei = el-sl; // milliseconds return (int) (ei/(1000*60*60*24))를 기준으로 간격 일을 계산합니다.
마찬가지로 동일한 방법을 사용하여 시간, 분, 초 등을 계산할 수 있습니다. 참고 : 위의 방법은 시간에 따라 완전히 계산되며 때로는 다음과 같이 만족스럽지 않습니다.
startday = "2006-10-11 20:00:00"Endday = "2006-10-12 8:00:00"
계산 결과는 0이지만 계산 결과가 1이 될 수 있습니다.이 시간에 다음 방법을 사용할 수 있습니다.
인수를 통과하기 전에 다음과 같은 다음과 같은 종말 시간을 먼저 설정하십시오.
endday.set (calendar.hour_of_day, 23); endday.set (calendar.minute, 59); endday.set (calendar.second, 59); endday.set (calendar.millisecond, 59);
당신이 그것을 전달하면, 결과는 우리가 원하는대로 될 것입니다. 그러나 위의 메소드가 번거로움을 발견하면 다음 방법을 참조 할 수 있습니다.
(3) 하루 횟수를 정확하게 계산하는 방법을 개선
public int getDaysbetween (Calendar D1, Calendar D2) ... d1.get (calendar.day_of_year); int y2 = d2.get (calendar.year); if (d1.get (calendar.year)! = y2) ... {d1 = (calendar) d1.clone (); {days += d1.getactualmaxumum (calendar.day_of_year); // d1.add (calendar.year, 1);} while (d1.get (calendar.year)! = y2);} 반환 일;}현재 시스템 시간을 얻으십시오.
public static string getsystemtime () {date date = new date (); simpledateformat df = new simpledateformat ( "yyyy-mm-dd hh : mm : ss"); return df.format (date);} // 문자열을 시간 유형으로 변환 할 수 있습니다 (simpleate format의 형식과 동일하게 문자열이 될 수 있습니다). java.text.simpledateformat sdf = new java.text.simpledateformat ( "m/dd/yyyy hh : mm : ss a", java.util.locale.us); java.util.date d = sdf.parse ( "5/13/2003 10:31:31:31:31:31:31:31: simpledateformat ( "yyyy-mm-dd hh : mm : mm : ss"); 문자열 mdateTime1 = formatter.format (d); // calendar cal = calendar.getInstance (); // simplededateformat formatter = new simpledateformat ( "yyyy-mm-dd hh : mm : ss"); simpledateformat formatter = new simpledateformat ( "yyyy-mm-dd hh : mm : mm : ss gedf w w w ef"); 문자열 mdatetime = formatter.format (cal.gettime ()); // 1 년 전 날짜 java.util.date mydate = new java.util.date (); long mytime = (mydate.gettime ()/1000) -60*60*60*24*365; mydate.settime (mytime*1000); String mdate = formatter.format (mydate); // 내일 날짜 mydate = new java.util.date (); mytime = (mydate.gettime ()/1000)+60*60*24; mydate.settime (mytime*1000); mdate = formatter.format (mydate); // 두 번 단순한 날짜 my simpledateformat ( "yyyy-m dd"); myformatter.parse ( "2003-05-1"); java.util.date mydate = myformatter.parse ( "1899-12-30"); long day = (date.gettime ()-mydate.gettime ())/(24*60*60*1000); // new Simpledate Format ( "yyyyy-mymmpdd (24*60*60*1000); // HH : MM : SS "); java.util.date date1 = format.parse ("2002-02-28 23:16:00 "); Long Time = (date1.gettime ()/1000)+60*30; date1.settime (time*1000); String mydate1 = formatter.format (date1); // 연도, 월, 주, 날짜 simplededateformat formatter2 = new simpledateformat ( "yyyy-mm fe"); 금요일 "); simpledateformat formatter3 = new simpledateformat ("yyyy-mm-dd "); String mydate2 = format3.format (date2); // 요일을 찾으십시오. mydate = myformatter.parse ("2001-1-1 "); Simplededate Formatter4 = New Simpledateformat ("e ");웹 애플리케이션을 개발할 때는 다양한 데이터베이스 날짜 유형에 대한 프로그램의 현재 유형마다 다양한 전환을해야합니다. 해당 데이터베이스 데이터가 Oracle의 날짜 유형, 즉 연도, 월 및 일만 필요한 경우 java.sql.date 유형을 사용하도록 선택할 수 있습니다. 해당 데이터베이스 데이터가 MSSQLServer 데이터베이스의 DateTime 유형 인 경우, 연도, 월, 일, 시간, 분 및 두 번째가 필요한 경우 Java.SQL.Timestamp 유형을 선택하십시오.
DateFormat을 사용하여 시간과 날짜의 형식을 정의하고 문자열로 바꿀 수 있습니다.
package personal.jessica; import java.util.date; import java.util.calendar; import java.sql.timestamp; import java.text.dateformat; import java.text.simpledateformat; import java.util.locale; class timest {timest am a the timest p (timest am)로 변환합니다. java.sql.timestamp) *@param datestring string timestamp *@return datatime timestamp */public final static java.sql.timestamp string2time (String Datestring)으로 java.text.parseexception {dateformat dateformat; dateformat = new simpledateformat ( "yyyyyymm mmd datestring java.text.parseexception {"yyyyymm mmd. kk : mm : ss.sss ", locale.english); // 형식 설정 // dateformat = new SimpledateFormat ("yyyy-mm-dd kk : mm : ss ", locale.english); dateformat.setLenient (false); java.util.date timedate = dateformat.parse (datestring); // util type java.sql.timestamp datetime = new java.sql.timestamp (timedate.gettime ()); // timestamp type, timedate.time.get the the the the the the the the the strents a methet a methet a strents. 날짜 (java.sql.date) *@param datestring 날짜로 변환 해야하는 문자열 *@return datatime 날짜 */public final static java.sql.date string2date (String Datestring)는 java.lang.exception {dateformat dateformat; dateformat = new simpledateformat ( "yyyyyyy-dd." locale.english); dateformat.setLenient (false); java.util.date timedate = dateformat.parse (datestring); // util type java.sql.date datetime = new java.sql.date (timedate.gettime ()); // sql return dateTime;} public void main (string ta) DATE (); 참고 :이 장소에서 DA.GetTime ()는 긴 값 시스템을 가져옵니다. out.out.println (da.gettime ()); // 첫 번째 방법으로 변환 // 첫 번째 방법 : 새 timestamp (long) timestamp t = new timestamp (new Date (). gettime ()); System.out.println (t); // 두 번째 방법 : timestamp (int 연도, int 달, int 날짜, int 시간, int minute, int second, int nano) timestamp tt = new timestamp (calendar.getinstance (). get (calendar.year) - 1900, calendar.getinstance (). Calendar.date), calendar.getInstance (). get (calendar.hour), calendar.getInstance (). get (calendar.minute), calendar.getInstance (). java.sql.date stotimestamp = "2005-8-18 14 : 21 : 12.123"; // java.sql.timestamp 날짜 1 = String2date (stodate)로 변환하는 데 사용되는 스탠드 문자열; timestamp date2 = string2time (stotimestamp); system.out.println ( "+날짜 : ////1); to java.sql.timestamp 날짜 1 = string2date (stotimestamp); system.out.println ( "date :"+date : "+date2.tostring ()); // java.sql.timestamp 날짜 2 = String2time (stotimestamp); SystemStamp (timestamp :"); tostack} catch (예외 e) {e.printstacktrace ();}}}예는 다음과 같습니다.
자바 코드
패키지 테스트; import java.text.dateformat; import java.text.parseexception; import java.text.simpledateformat; import java.util.calendar; import java.util.date; import java.util.hashtable; import javax.swing.joptionpane (string) {string state state (problean boolean isdate) a [] = S.Split ( "-"); 부울 flg = true; if (! simpledateformat ( "yyyy-mm-dd"); ret = df.format (df.parse (s)). equals (s);} catch (parseexception e) {ret = false;} return ret;} public object dateinfo (문자열 a [] = s.split ( "-", 2); Hashtabable fest = New Hashtable (); Fest.put ( "01-01", "New Year 's Day"); Fest.put ( "02-14", "Valentine's Day"); Fest.put ( "03-12", "Arbor Day"); Fest.put ( "03-15", "Consumer Day"); "04-01", "04-01" Festival "); Festire.put ("05-01 ","Labor Day "); Fest.put ("06-01 ","Children 's Day "); Fest.put ("07-01 ","Party Day 중심 "); Fest.put ("08-01 ","Army Day "); Fest.put ("09-10 "," "10-10") day "); fest.put ("12-25 ","Christmas "); if (fest.containskey (a [1])) {return fest.get (a [1]);} else {return"no holiday ";}} public string xingzuo (날짜 s) {calendar cal = calendar.getinstime (s); string xingzu =" "; day = cal.get (calendar.day_of_year); if ((cal.get (calendar.year)%4 == 0) && (cal.get (calendar.year)%100! = 0) || (cal.get (calendar.year)%400 == 0)) {if (day> = 1 && day <= 19) || (day> = 357 && day <= 366)) {xingzuo = "scorpio";} else if (day> = 20 && day <= 49) {xingzuo = "aq && day <= 110) {xingzuo = "aries";} else if (day> = 111 && day <= 141) {xingzuo = "taurus";} else if (day> = 142 && day <= 173) {xingzuo = "gemini"; else (day> = 204 && day <= 235) {xingzuo = "leo";} else if (day> = 236 && day <= 266) {xingzuo = "virgo";} else if (day> = 267 && day <= 296) {xingzuo = ""libra "; && day <= 326) {xingzuo = "scorpio";} else if (day> = 327 && day <= 356) {xingzuo = "sauvignon";}} else {if (day> = 1 && day <= 357 && day <= 366)) {xingzuo = ""xingzuo = " if (day> = 20 && day <= 48) {xingzuo = "aquarius";} else if (day> = 49 && day <= 79) {xingzuo = "pisces";} else if (day> = 80 && day <= 109) {xingzuo = "Aries"; "taurus";} else if (day> = 141 && day <= 172) {xingzuo = "gemini";} else if (day> = 173 && day <= 202) {xingzuo = "cancer";} else if (day> = 203 && day <= 234) {xingzuo = "eleo"; && day <= 265) {xingzuo = "Virgo";} else if (day> = 266 && day <= 295) {xingzuo = "libra";} else if (day> = 296 && day <= 325) {xingzuo = "scorpio"; "saucy";}} return xingzuo;} 공개 날짜 parsedate (string s) {simpledateformat bartdateformat = new simpledateformat ( "yyyy-mm-dd"); try {date date3 = bartdateformat.parse (s); date3 = bartdateformat.parse (s); ret.3; null;}} public static void main (String [] args) {Calendar cal = calendar.getInstance (); test2 = new test2 (); String date1 = joptionpane.showinputDialog ( "날짜를 입력하십시오. 형식은 2000-10-15"); while (! bartdateformat2 = new simpledateformat ( "yyyy-mm-dd"); 날짜 날짜 2 = test2.parsedate (date1); String festinfo = (string) test2.dateinfo (date1); System.out.println (bartdateformat1.format (date2)+","+festinfo+","+test2.xingzu (date2)); day = joptionpane.showinputDialog ( "쿼리 날짜 정보를 입력하십시오"); cal.settime (date2); cal.add (calendar.date, integer.parseint (day)); String); date5 = bartdateformat2.format (cal.gettime ()); festinfo = (string) test2.dateinfo (date5); system.out.println (bartdateformat1.format (cal.gettime ())+","+festinfo+","+test2.xingzuo (cal.gettime ());요약
위는이 기사에서 Java 시간 및 날짜 사용 및 쿼리 코드에 대한 자세한 설명입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!