主要代码:
1 import java.text.DateFormat; 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4 5 6 public class TestDateTimeAdd 7 { 8 9 public static void main(String[] args)10 {11 try12 {13 subDateTime("2015-12-09 15:55:30", "2015-12-09 15:57:38");14 }15 catch (Exception e)16 {17 e.printStackTrace();18 }19 }20 21 22 public static void subDateTime(String beginTime,String endTime) throws Exception23 {24 25 /*26 * 时间转化样式27 */28 DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");29 30 /*31 * 把字符类型的时间转化为标准时间样式32 */33 Date firstDateTimeDate = format.parse(beginTime);34 Date secondDateTimeDate = format.parse(endTime);35 36 /*37 * 得到时间的总毫秒数38 */39 long firstDateMilliSeconds = firstDateTimeDate.getTime();40 long secondDateMilliSeconds = secondDateTimeDate.getTime();41 42 /*43 * 两个日期相减44 */45 long subDateMilliSeconds = secondDateMilliSeconds - firstDateMilliSeconds;46 47 //毫秒转化为秒48 int totalSeconds = (int) (subDateMilliSeconds/1000);49 50 /*51 * 毫秒数转化为总天数52 */53 // int days = totalSeconds / (3600*24);54 int days_remains = totalSeconds % (3600*24);55 56 /*57 * 天数转化为时58 */59 int hours = days_remains/3600;60 int hours_remains = days_remains % 3600;61 62 /*63 * 得到分钟数64 */65 int minutes = hours_remains / 60;66 67 /*68 * 得到秒数69 */70 int seconds = hours_remains % 60;71 72 String outTime = ((hours < 10) ? "0" : "") + hours + ":"+73 ((minutes < 10) ? "0" : "") + minutes + ":" +74 ((seconds < 10) ? "0" : "") + seconds;75 System.out.println(outTime);76 }77 }