Jakeinzah
Jakeinzah

Reputation: 25

Formatting time to remove unnecessary 00's from the timer

I'm trying to clean up my timer for my application but im having difficulties getting it to do what I want.

Would anyone know how to format H:M:S and remove the 00's?

Example the time may start like this: 12:34:56 (hh:mm:ss)

But once the time reaches lets say 00:34:56, remove the remaining 00's, I'm a bit worried about performance which is why I'm here to find the more efficient way to format the time as this will be called a lot.

Would String.format("%02d:%02d", m, s).replaceAll("00:",""); be a wise choice?

Thanks.

Upvotes: 0

Views: 87

Answers (3)

VGR
VGR

Reputation: 44335

You have practically answered your own question. Just turn your thoughts into code.

What you need:

If the time is less than one hour, show only minutes and seconds; else, show hours, minutes and seconds.

Your code should read like the spoken version:

if (hours < 1) {
    text = String.format("%02d:%02d", minutes, seconds);
} else {
    text = String.format("%02d:%02d:%02d", hours, minutes, seconds);
}

Simple, clean, fast, and easy for future programmers (including yourself, a year from now) to understand.

Upvotes: 1

Gavriel Raanan
Gavriel Raanan

Reputation: 21

I assume you could be negligibly faster by just checking the first 2 characters:

if (timeString.charAt(0) == '0' && timeString.charAt(1) == '0')
   timeString = timeString.substring(3);

I don't necessarily think that's great code, but 2 character checks would probably be faster than a larger string search. Not by much, though, so I doubt it's worth it.

(Made a fix based on the comment, changing == '1' to == '0' )

Upvotes: 2

F.Igor
F.Igor

Reputation: 4350

Using a regular expression, you can delete only the first section '00:' using (It's only for deleting the hour part in a HH:MM::SS time format)

String.format("%02d:%02d", m, s).replaceAll("^00:","");

^ is a character to mark the beginning of a line

Upvotes: 2

Related Questions