美文网首页
java 秒转化为时分秒

java 秒转化为时分秒

作者: 平面小狮子 | 来源:发表于2019-08-01 16:49 被阅读0次

项目开发过程中要算两个时间的差值以时分秒的形式进行展示运行时长,于是乎就有了下面的代码:

// 计算出两个时间的时间差

public static void main(String[] args) {

// 当前日期

    LocalDateTime localDateTime = LocalDateTime.now();

    // 传进来的Date日期转LocalDate

    Date date =new Date();

    Instant instant = date.toInstant().plus(Duration.ofHours(1));

    ZoneId zoneId = ZoneId.systemDefault();

    LocalDateTime localDateTime1 = LocalDateTime.ofInstant(instant, zoneId);

    // 计算时间差

    Duration duration = Duration.between(localDateTime, localDateTime1);

    System.out.println("second:  "+duration.getSeconds());

    String str =secondToTime(duration.getSeconds());

    System.out.println("str: "+str);

}

// 秒转换成时分秒

private static StringsecondToTime(long second) {

long days = second /86400;//转换天数

    second = second %86400;//剩余秒数

    long hours = second /3600;//转换小时数

    second = second %3600;//剩余秒数

    long minutes = second /60;//转换分钟

    second = second %60;//剩余秒数

    if (0 < days){

return days +":"+hours+":"+minutes+":"+second;

    }else {

return hours+":"+minutes+":"+second;

    }

}

运行时长

相关文章

网友评论

      本文标题:java 秒转化为时分秒

      本文链接:https://www.haomeiwen.com/subject/ssdcdctx.html