如何在Java中格式化时间间隔? [英] How to format time intervals in Java?

查看:369
本文介绍了如何在Java中格式化时间间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了J2SE应用程序,该应用程序需要以毫秒为单位将两次格式化为代表两次间隔的字符串.

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

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

,我想得到类似"00:02:00"的信息.这很简单,但是我需要设置格式间隔,该间隔的长度从几秒钟到几年不等-因此库应该处理它.理想情况是,该库是否可以根据国家/地区的习惯(如果有)来格式化间隔.

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).

我搜索了所有问题,答案和解决方案,可能是Apache Commons的Jodatime或Lang库.您能给我一些建议吗,这些库中的哪个库可以更好地解决我的要求?预先谢谢你.

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.

推荐答案

您可以使用标准Java Calendar最多间隔一天(24小时).但是,不能长时间(几天,几年)使用此技巧,

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()));

这篇关于如何在Java中格式化时间间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆