开发者

Convert long time difference to format HH:mm [Java]

How can I convert the difference of the current time a given time开发者_如何学C to create a string with the time format: HH:mm ? ex. 18:36

I did the following but, it is not 24Hour format, it will add AM/PM to the end, and it is 3 hours off.

        java.util.Date today = new java.util.Date();
        java.sql.Timestamp ts1 = new java.sql.Timestamp(today.getTime());

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
        java.util.Date parsedDate = dateFormat.parse(time);
        java.sql.Timestamp ts2 = new java.sql.Timestamp(parsedDate.getTime());

        long nowTime = ts1.getTime();
        long givenTime = ts2.getTime();

        long timeDiff = givenTime - nowTime;

        //convert to string
        java.util.Date d = new java.util.Date(timeDiff);
        result = DateFormat.getTimeInstance(DateFormat.SHORT).format(d);
        //Outputs: 6:56 PM for example


Once easy thing you can do is call getTime() for both dates and then subtract them like so:

long timeDiff = today.getTime() - ts1.getTime()

That should give you the difference in miliseconds between the two times. After that you know that one second is 1k miliseconds, 1min i 60s, 1h is 60 minutes and so on.


Take a look at Commons Lang DurationFormatUtils.

Or Joda-Time's PeriodFormatter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜