计算时间差:

注:时间是以毫秒来算的,一天等于24小时,一小时等于60分钟,一分钟等于60秒,一秒等于1000毫秒!

 private int formatDate(Date nowDate, Date sqlDate){
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   String newDate = df.format(nowDate);
   String sqlDate1 = df.format(sqlDate);
   try {
      nowDate = df.parse(newDate);
      sqlDate = df.parse(sqlDate1);
   } catch (ParseException e) {
      e.printStackTrace();
   }
   Long time =  nowDate.getTime();
   Long time2 =  sqlDate.getTime();
   int day = (int) ((time - time2) / (24*3600*1000));
   return day;
}

一.毫秒

int millisecond = (int)(time - time2) / (1)

二.秒秒

int second = (int)(time - time2) / (1000 )

1000 为 1 秒钟

三.分

int Minutes = (int)(time - time2) / (1000 * 60 )

1000 为 1 秒钟 1000*60 为 1 分钟

四.时

int hours = (int)(time - time2) / (1000 * 60 * 60)

1000 为 1 秒钟 100060 为 1 分钟 100060*60 为 1 小时

五.天

int day = (int) ((time - time2) / ( 1000 * 60 * 60 * 24);

1000 为 1 秒钟 100060 为 1 分钟 10006060 为 1 小时 1000 60 60 24 为 1 天

例子: 2021-01-01 00:00:00 和 2020-12-12 00:00:00

一,相毫秒,秒,分,时,天

@Test
public  void test(){
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   try {
      System.out.println(formatDate(df.parse("2021-01-01 23:59:59"),df.parse("2020-12-12 00:00:00")));
   } catch (ParseException e) {
      e.printStackTrace();
   }
}

结果:

毫秒:1728000000 秒:1728000 分: 28800 时: 480 天 20

Last modification:September 25th, 2022 at 08:43 pm
如果觉得我的文章对你有用,请随意赞赏