4

I have Hours, Minutes and Seconds stored in long variables. Pretend that the current values of these are:

long seconds = 30;
long minutes = 0
long hours = 0;

When I convert these to strings and print them:

Long.toString(Hours)+":"+Long.toString(Minutes)+":"+Long.toString(Seconds)

The output looks like

0:0:30

I want:

00:00:30

I'm assuming this should be straight forward but I cant work it out..

BigFatToe
  • 63
  • 1
  • 2
  • 4
  • 2
    `System.out.printf("%02d:%02d:%02d", hours, minutes, seconds)`. Or `String.format`, or some variant. – Andy Turner Aug 25 '16 at 11:37
  • you can find there some exampels: [Adding leading Zeroes](http://stackoverflow.com/questions/275711/add-leading-zeroes-to-number-in-java) – Soengend Aug 25 '16 at 11:42
  • It's a good manner to mark solutions by clicking on a gray tick under the downvote gray triange next to the answer. – xenteros Aug 25 '16 at 14:27

2 Answers2

3

Try the following:

System.out.printf("%02d:%02d:%02d", hours, minutes, seconds);

If you want to store the String in a variable do the following:

String s = String.format("%02d:%02d:%02d", hours, minutes, seconds);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
xenteros
  • 15,586
  • 12
  • 56
  • 91
-1

use String.format("%02d", your number)

for more info read javadoc

Durgpal Singh
  • 11,481
  • 4
  • 37
  • 49