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+"年前";
}
}
}
}
}
}
}
linhuaming