如下代碼就是時間差計算(秒、分鐘、小時、天數、月份、年)java
package me.zhengjie; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.Test; public class DemoTest { @Test public void run1() { System.out.println("run1()"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); String startDateStr = "2012-01-20 00:00:00.000"; String endDateStr = "2019-11-01 00:00:00.000"; try { Date startDate = sdf.parse(startDateStr); Date endDate = sdf.parse(endDateStr); String timeDifference = this.convert(startDate, endDate); System.out.println(timeDifference); } catch (ParseException e) { e.printStackTrace(); System.out.println("日期格式化失敗"); } } public String convert(Date startDate,Date endDate) { long startTime = startDate.getTime();//獲取毫秒數 long endTime = endDate.getTime(); //獲取毫秒數 long timeDifference = endTime-startTime; long second = timeDifference/1000; //計算秒 if(second<60) { return second+"秒前"; }else { long minute = second/60; if(minute<60) { return minute+"分鐘前"; }else { long hour = minute/60; if(hour<24) { return hour+"時前"; }else { long day = hour/24; if(day<30) { return day+"天前"; }else { long month = day/30; if(month<12) { return day+"月前"; }else { long year = month/12; return year+"年前"; } } } } } } }