一、前言:
java获取当前时间戳的方法
image
1 2 3 4 5 6 | //方法 一(毫秒值) System.currentTimeMillis(); //方法 二(毫秒值) Calendar.getInstance().getTimeInMillis(); //方法 三(毫秒值) new Date().getTime(); |
以下代码就是时间差计算(秒、分钟、小时、天数、月份、年)
二、代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 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+"年前"; } } } } } } } |