How do I fill with 0 where nessessary when dealing with time.

T

tony

Hello!

I have this method that take number of seconds(numOfSec) and convert this
into a string with this format hh:mm:ss.
Now to my question there is a small problem when I have time component that
is < 10.
If I pass 7862 seconds to this method I get back "2:11:2" but I want to get
back "02:11:02".
I want this method to fill with 0 where nessesary.
Is it an easy way to do this or do I have to split each time component into
a string.

private string ConvStdTimeToTimeFormat(int numOfSec)
{
return Convert.ToString (sec/3600) + ":" + Convert.ToString ((sec %
3600) / 60 ) + ":" +
Convert.ToString ((sec % 3600) % 60);
}

//Tony
 
B

Barry Kelly

tony said:
I have this method that take number of seconds(numOfSec) and convert this
into a string with this format hh:mm:ss.
Now to my question there is a small problem when I have time component that
is < 10.
If I pass 7862 seconds to this method I get back "2:11:2" but I want to get
back "02:11:02".

Console.WriteLine(TimeSpan.FromSeconds(7862));

-- Barry
 
C

Claes Bergefall

private string ConvStdTimeToTimeFormat(int numOfSec)
{
DateTime dt = new DateTime((long) numOfSec * 10000000);
return dt.ToString("hh:mm:ss");
}

/claes
 
J

james.curran

In the more general case, to print a number with leading zeros, use the
print specifier "d", follwed by the number of digits desired:

private static string ConvStdTimeToTimeFormat(int numOfSec)
{
int hours = numOfSec/3600;
int minutes = ((numOfSec % 3600) / 60 );
int secs = ((numOfSec % 3600) % 60);

return String.Format("{0:d2}:{1:d2}:{2:d2}", hours, minutes, secs);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top