ImportJava.text.DateFormat;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;/*** Time is apart *@authorben*@version1.0* @date 2009-10-21 16:38:51*/ Public classDatedistance {/*** Two time difference between days *@paramOne time parameter 1: *@paramTime Parameter 2: *@returndifference in days*/ Public Static LongGetdistancedays (String str1, String str2)throwsexception{DateFormat DF=NewSimpleDateFormat ("Yyyy-mm-dd"); Date one; Date; LongDays=0; Try{ One=Df.parse (STR1); both=Df.parse (STR2); LongTime1 =One.gettime (); LongTime2 =Two.gettime (); Longdiff; if(time1<time2) {diff= Time2-time1; } Else{diff= Time1-time2; } Days= diff/(1000 * 60 * 60 * 24); } Catch(ParseException e) {e.printstacktrace (); } returnDays ; } /*** Two time difference between how many days how many hours how many seconds *@paramstr1 Time parameter 1 format: 1990-01-01 12:00:00 *@paramstr2 Time Parameter 2 format: 2009-01-01 12:00:00 *@returnlong[] The return value is: {days, hours, minutes, seconds}*/ Public Static Long[] Getdistancetimes (String str1, String str2) {DateFormat df=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Date one; Date; LongDay = 0; LongHour = 0; LongMin = 0; LongSEC = 0; Try{ One=Df.parse (STR1); both=Df.parse (STR2); LongTime1 =One.gettime (); LongTime2 =Two.gettime (); Longdiff; if(time1<time2) {diff= Time2-time1; } Else{diff= Time1-time2; } Day= diff/(24 * 60 * 60 * 1000); Hour= (diff/(* * +)-day * 24); Min= ((diff/(+))-day * 60-hour * 60); SEC= (diff/1000-day*24*60*60-hour*60*60-min*60); } Catch(ParseException e) {e.printstacktrace (); } Long[] times ={day, hour, Min, sec}; returnTimes ; } /*** Two time difference between how many days how many hours how many seconds *@paramstr1 Time parameter 1 format: 1990-01-01 12:00:00 *@paramstr2 Time Parameter 2 format: 2009-01-01 12:00:00 *@returnString return value: xx days xx hours xx minutes xx seconds*/ Public Staticstring Getdistancetime (String str1, String str2) {DateFormat df=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Date one; Date; LongDay = 0; LongHour = 0; LongMin = 0; LongSEC = 0; Try{ One=Df.parse (STR1); both=Df.parse (STR2); LongTime1 =One.gettime (); LongTime2 =Two.gettime (); Longdiff; if(time1<time2) {diff= Time2-time1; } Else{diff= Time1-time2; } Day= diff/(24 * 60 * 60 * 1000); Hour= (diff/(* * +)-day * 24); Min= ((diff/(+))-day * 60-hour * 60); SEC= (diff/1000-day*24*60*60-hour*60*60-min*60); } Catch(ParseException e) {e.printstacktrace (); } returnDay + "Days" + Hour + "hours" + min + "min" + sec + "SEC"; }}
Java two time difference between strings