java 格式化时间 小时,如何在Java中格式化时间间隔?

I create J2SE application and this application needs to format two times in milliseconds into a string that represents the interval between this two times.

long time1 = 1334331041677L; //Fri Apr 13 17:30:41 CEST 2012

long time2 = time1+1000*60*2; //Fri Apr 13 17:32:41 CEST 2012

and I would like to get something like "00:02:00". This would be simple, but I need to format interval which is long from few seconds up to several years - so the library should handle it. Ideally is if this library could format the interval according to the habbits of the country (if any).

I have searched throught the questions and answers and solution for me could be Jodatime or Lang library from Apache Commons. Could you provide me some recommendation which library from these solves my requirements in better way? Thank you in advance.

解决方案

You can use standard Java Calendar for intervals up to one day (24 hours). It is not possible to use this trick for longer periods (days, years), though...

long start = System.currentTimeMillis();

/*

* perform the measured activity here,

* let's say it will take 2 minutes 5 seconds => 125 seconds => 125000ms

*/

Thread.sleep(125 * 1000);

long stop = System.currentTimeMillis();

Calendar c = Calendar.getInstance();

c.set(Calendar.HOUR_OF_DAY, 0);

c.set(Calendar.MINUTE, 0);

c.set(Calendar.SECOND, 0);

c.set(Calendar.MILLISECOND, 0);

c.setTimeInMillis(c.getTimeInMillis() + (stop - start));

DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");

System.out.println(df.format(c.getTime()));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值