java实现两个日期时间差算出分钟差

java实现两个日期时间差算出分钟差

1.用代码实现两个时间的分钟差

// 获取时间
 LocalDateTime time1 = "2020-06-08 09:28:45";
 LocalDateTime time2 = "2020-08-01 16:34:56";
 //计算出两个时间的差值
 Duration differenceValue = Duration.between(time1 ,time2 );
 // 获取的是两个时间相差的分钟数,如果想要相差小时数就调用toHours()
Long minutesTime = differenceValue .toMinutes();
Long minutesTime = differenceValue .toHours();

用sql实现两个时间差算出分钟差
// UNIX_TIMESTAMP是将时间转化为时间戳,时间除以60是要转化为分钟时间戳
// CAST是用来转类型的
  SELECT
  CAST(UNIX_TIMESTAMP(time1)/60 AS SIGNED) as time1,
  CAST(UNIX_TIMESTAMP(time2)/60 AS SIGNED) as time2
  FROM tableName;
//拿到时间戳之后就可以直接运算了

拿到两个时间的分钟差之后,可以根据时间的换算,得到自己想要的形式,下面这个工具类是根据分钟换算成以下的形式

  public static String translateTimeUtil(Long time){
        Long differTime = time;
        //两个时间戳相差多少分钟
        String dataTime ="";
        if (differTime >= 525600){
            int year = differTime.intValue()/525600;
            int day = (differTime.intValue()-525600*year)/1440;
            int hour =(differTime.intValue()-525600*year-1440*day)/60;
            dataTime = year + "年" +day + "天" + hour + "小时";
        }else {
            if (differTime >= 1440 ) {
                int day = differTime.intValue() / 1440;
                int hour = (differTime.intValue()-1440*day)/60;
                dataTime = day + "天" + hour + "小时";
            }else if (differTime <60){
                dataTime = differTime + "分钟";
            } else {
                int hour = differTime.intValue() /60;
                int minute = differTime.intValue()%60;
                dataTime = hour + "小时" + minute +"分钟";
            }
        }
        return dataTime ;
    }

猜你喜欢

转载自blog.csdn.net/weixin_46128517/article/details/107560166