话不多说,现附上代码:
String bxsj = "2019-07-08 07:58:00"; String clsj = "2019-07-08 12:52:02"; SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date bx = null; Date cl = null; try { bx = sf.parse(bxsj); cl = sf.parse(clsj); } catch (ParseException e) { e.printStackTrace(); } //通过字符串创建两个日期对象 //得到两个日期对象的总毫秒数 long firstDateMilliSeconds = bx.getTime(); long secondDateMilliSeconds = cl.getTime(); System.out.println("bx:"+firstDateMilliSeconds+"---"+"cl:"+secondDateMilliSeconds); //得到两者之差 long firstMinusSecond =secondDateMilliSeconds - firstDateMilliSeconds; System.out.println("两者差:"+firstMinusSecond); //毫秒转为秒 long milliSeconds = firstMinusSecond; int totalSeconds = (int)(milliSeconds / 1000); //得到总天数 int days = totalSeconds / (3600*24); int days_remains = totalSeconds % (3600*24); //得到总小时数 int hours = days_remains / 3600; int remains_hours = days_remains % 3600; //得到分种数 int minutes = remains_hours / 60; //得到总秒数 int seconds = remains_hours % 60; String clts=""; if(days!=0){ clts+=days+"天"; }else if(hours!=0){ clts+=hours+"小时"; }else if(minutes!=0){ clts+=minutes+"分钟"; }else if(seconds!=0){ clts+=seconds+"秒"; } System.out.println(clts);
结果为:
bx:1562543880000---cl:1562561522000
两者差:17642000
4小时
再附上可能出现的错误之处:
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
此时出现的错误结果为:
bx:1562543880000---cl:1562518322000
两者差:-25558000
-7小时
综上所述: 注意字符格式转换为时间时,格式的正确书写为:
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");