Function to Format hours and Minutes

interclubs
interclubs used Ask the Experts™
on
I have a bunch of different times (hours:minutes) and while some of them look like this:
12:25
1:20

other looks like this:
00:1
0:2
2:
So I need a function that will always remove the two leading zeros, if the time is 00:20. It would become :20
Will always make sure that there is a zero in minutes so :1 would be :10
and if there are no minutes, it always add a :00
so 2 or 2: would become 2:00


Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Multitechnician
Top Expert 2014
Commented:
var a = "2:";

a = a.replace(/^00:/,":"); // will always remove the two leading zeros
a = a.replace(/(:\d{1}$)/,"$10"); // Will always make sure that there is a zero in minutes
a = a.replace(/(\d{1,2}:)$/g,"$100"); //  if there are no minutes, it always add a :00

alert(a);

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial