1 /**2 * Calculate the difference of two time, the number of days, years, months, minutes, number of seconds3 * 4 * @paramDatetype The type of difference between two times to get, for example, the number of days to get a two time difference? or the number of hours?5 * @paramStartDate Start Time6 * @paramEndDate End Time7 * @returnDatetype value between (end time-start time)8 */9 Public Static intDateDiff (String datetype, date startdate, date endDate) {Ten One /*find the number of years between StartDate and EndDate*/ A if("Y". Equalsignorecase (datetype) | | "YY". Equalsignorecase (Datetype)) { -Calendar Calendar =calendar.getinstance (); - Calendar.settime (startdate); the intStartYear = Calendar.get (calendar.year);//year of the current year - Calendar.settime (endDate); - intEndyear =Calendar.get (calendar.year); - returnEndyear-StartYear; + } - /*find the number of months between StartDate and EndDate*/ + if("M". Equals (Datetype) | | "MM". Equals (Datetype)) { ACalendar Calendar =calendar.getinstance (); at Calendar.settime (startdate); - intStartmonth = Calendar.get (calendar.month) +calendar.get (calendar.year) *12;//month = year of the current year *12 + month of the current year, same as - Calendar.settime (endDate); - intEndmonth = Calendar.get (calendar.month) +calendar.get (calendar.year) *12; - returnEndmonth-Startmonth; - } in /*find the number of days between StartDate and EndDate*/ - if("D". Equalsignorecase (datetype) | | "DD". Equalsignorecase (Datetype)) { to LongStartTime =startdate.gettime (); + LongEndTime =enddate.gettime (); - return(int) ((endtime-starttime)/1000/60/60/24);//days = number of milliseconds between (end time-start time)/(number of milliseconds per day) the } * /*find the number of hours between StartDate and EndDate*/ $ if("H". Equalsignorecase (datetype) | | "HH". Equalsignorecase (Datetype)) {Panax Notoginseng LongStartTime =startdate.gettime (); - LongEndTime =enddate.gettime (); the return(int) ((endtime-starttime)/1000/60/60); + } A /*find the number of minutes between StartDate and EndDate*/ the if("M". Equals (Datetype) | | "MM". Equals (Datetype)) { + LongStartTime =startdate.gettime (); - LongEndTime =enddate.gettime (); $ return(int) ((endtime-starttime)/1000/60); $ } - /*find the number of seconds between StartDate and EndDate*/ - if("S". Equalsignorecase (datetype) | | "SS". Equalsignorecase (Datetype)) { the LongStartTime =startdate.gettime (); - LongEndTime =enddate.gettime ();Wuyi return(int) ((Endtime-starttime)/1000); the } - Wu return0; - About}
Implementing the DATEDIFF function in SQL Server with Java