开发者

Android: Format milliseconds into >60 seconds when no minute format is given

开发者 https://www.devze.com 2023-03-26 04:01 出处:网络
I got a millisecond value. I开发者_运维百科 want to use a format string, to format those milliseconds into a time format. e.g. 45000ms = 45s or 0m 45s or whatever. So this is no special thing. I used

I got a millisecond value. I开发者_运维百科 want to use a format string, to format those milliseconds into a time format. e.g. 45000ms = 45s or 0m 45s or whatever. So this is no special thing. I used SimpleDateFormat for this, but now comes my problem:

61000ms ends up in 1m 1s. This is okay for me, IF there is a minute given in the format string. But when there is no minute given in the format string, it should print out 61s instead of just 1s.

Is there any easy way to achieve this? Currently I dont see it without doing any ugly string formatting code.

I hope you can help me :)

Thanks in advanced! slain

Edit:

For better understanding: you got 65400 milliseconds.

format string has minutes, seconds, milliseconds: 1m 5s 400ms

format string has minutes and seconds: 1m 5s

format string has seconds: 65s

format string has seconds and milliseconds: 65s 4ms

format string has minutes and milliseconds: 1m 5400ms


I'm not sure what exactly you are trying to convert but have a look at time units.


If I understand correctly, you are given a number of milliseconds, and a time format string, and need to produce a correctly formatted time? If not, ignore the rest of this...

Maybe not the BEST way, but kind of a nice waterfall: Convert the milliseconds to a set of integers for days, hours, minutes, seconds (or more, or less, depending on the expected range), and then iterate forward through the format string. If day is present, great, stick the number of days in there. If not, skip it, multiply by 24 and add to hours. Do the same for hours->minutes, minutes->seconds, and you should end up with it correctly formatted, even if with weird formats (like days and seconds but not minutes).


Not exactly sure what you're looking for, but you can parse milliseconds like so;

private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd MMM yyyy");

public static void main(String[] args) {
    final long millis = System.currentTimeMillis();
    System.out.println(DATE_FORMAT.format(new Date(millis))); // Prints 05 Aug 2011
}

Obviously, you can tweak the date format as necessary to display seconds, milliseconds, etc.

0

精彩评论

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