为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用Java计算时间跨度并格式化输出?

如何使用Java计算时间跨度并格式化输出?

犯罪嫌疑人X 2019-10-11 14:29:18
我想花两次(从纪元以来的秒数),以如下格式显示两者之间的差异:2分钟1小时15分钟3小时9分钟1分钟前1小时2分钟前我该怎么做?
查看完整描述

5 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

Date start = new Date(1167627600000L); // JANUARY_1_2007

    Date end = new Date(1175400000000L); // APRIL_1_2007



    long diffInSeconds = (end.getTime() - start.getTime()) / 1000;


    long diff[] = new long[] { 0, 0, 0, 0 };

    /* sec */diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);

    /* min */diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;

    /* hours */diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;

    /* days */diff[0] = (diffInSeconds = (diffInSeconds / 24));


    System.out.println(String.format(

        "%d day%s, %d hour%s, %d minute%s, %d second%s ago",

        diff[0],

        diff[0] > 1 ? "s" : "",

        diff[1],

        diff[1] > 1 ? "s" : "",

        diff[2],

        diff[2] > 1 ? "s" : "",

        diff[3],

        diff[3] > 1 ? "s" : ""));


查看完整回答
反对 回复 2019-10-11
  • 5 回答
  • 0 关注
  • 680 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信