'is there a way to get always 2-digits values with TimeStamp in Java? [duplicate]

Let's say i have several TimeStamp objects and i want to know the difference between 2 of them in terms of minutes and seconds.

TimeStamp timestamp1 = new TimeStamp(System.currentTimeMillis());
TimeStamp timestamp2 = new TimeStamp(System.currentTimeMillis());

if i use the method getSeconds (but the concept can be adapted to minutes and hours too), for example, the expected output is "SS".

But when i try to get the difference between the 2 objects (something like:

long differenceInSeconds = (timestamp1.getseconds() - timestamp2.getSeconds());

Now the expected output is just the difference between 2 numbers, so clearly it can be 0, 5, 13, ...

What if i wanted to always have values formatted in XX? 0 would be 00, 13 would be 13 and going on.

Maybe there is some class, or method,regarding timestamp which i'am unaware of?



Solution 1:[1]

What you want can be achieved in the following way

long differenceInSeconds = (timestamp1.getseconds() - timestamp2.getSeconds());
String.format("%02d", differenceInSeconds)

The flag %02d means it will convert it into a 2 digit string if the passed number is less than 2 digits. So if you pass 5 it will be converted to string 05. If you pass 13 it will remain 13.

Solution 2:[2]

I think the reason why it is not padded is because the Method returns an int value, which is not padded by default. The only way to get a padded value is converting your number to a string and then add leading zeros.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Panagiotis Bougioukos
Solution 2 K. K.