string.format and timespan

  • Thread starter Thread starter RicercatoreSbadato
  • Start date Start date
R

RicercatoreSbadato

I'd like to print a TimeSpan variable in this way:

00:00:00 --> hh:mm:ss

(whitout the milliseconds)

how can I do it?
 
I think you can do it like this:
TimeSpan ts = new TimeSpan(23,40,3);
DateTime d = new DateTime(ts.Ticks);
string time = d.ToString("hh:mm:ss");
--
Muhammad Mosa
Software Engineer & Solution Developer
MCT/MCSD.NET
MCTS: .Net 2.0 Web Applications
MCTS: .Net 2.0 Windows Applications
 
00:00:00 can't be displayed as hh:mm:ss though. You need HH:mm:ss for that.

If you need to show total hours this method won't work if the TimeSpan exceeds 24 hours.
If this is an issue you can always format your string the hard way

TimeSpan s = dateTimeB - dateTimeA;
string time = ((int)s.TotalHours).ToString().PadLeft(2, '0') +":" + s.Minutes.ToString().PadLeft(2, '0') + ":" + s.Seconds.ToString().PadLeft(2, '0');
 
Morten Wennevik said:
00:00:00 can't be displayed as hh:mm:ss though. You need HH:mm:ss for that.

If you need to show total hours this method won't work if the TimeSpan exceeds 24 hours.
If this is an issue you can always format your string the hard way

TimeSpan s = dateTimeB - dateTimeA;
string time = ((int)s.TotalHours).ToString().PadLeft(2, '0') +":" +
s.Minutes.ToString().PadLeft(2, '0') + ":" +
s.Seconds.ToString().PadLeft(2, '0');

Or, slightly more concisely:

TimeSpan ts = new TimeSpan(12, 6, 7);
string x = string.Format ("{0:00}:{1:00}:{2:00}", (int)ts.TotalHours,
ts.Minutes, ts.Seconds);
 

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

Back
Top