开发者

Convert an amount of seconds into a formatted string using midp/blackberry

I'm trying to convert an amount of seconds into a formatted string using midp

Below is code I'm using, the problem is that when I run this on a device (BlackBerry), 2 hours are being appended. So - formatSecondsAsDuration(1000) returns "00:02:01" What I expect is "00:00:01"

I think this is occuring since SimpleDateFormat is using my locale ? I am unable to use the method setTimeZone to set the timezone to UTC which I think could fix the issue.

public static String formatSecondsAsDuration(long second开发者_运维问答) {

    Date date = new Date(second);

     return new SimpleDateFormat("HH:mm:ss").format(date);

}

I have already asked a similar question - Convert int val to format "HH:MM:SS" using JDK1.4 But have since found was not fully suitable


What about something really simple like:

public static String formatSecondsAsDuration(long seconds) {
    long hour = seconds / 60 / 60;
    long min = (seconds / 60) - (hour * 60);
    long sec = seconds - (min * 60) - (hour * 60 * 60);

    return (hour < 10 ? "0" : "") + hour + ":" + 
           (min < 10 ? "0" : "") + min + ":" +
           (sec < 10 ? "0" : "") + sec;
}

Just make sure you actually pass seconds (as indicated by the parameter name), or else modify the code above to handle milliseconds if that's what you're actually needing.

EDIT: I just ran across this method today that looks like it does exactly what you want and is already built-in to the BB API: DateTimeUtilities.formatElapsedTime()

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜