467,877 Members | 1,219 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,877 developers. It's quick & easy.

string.format and timespan

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?

Aug 5 '06 #1
  • viewed: 60972
Share:
3 Replies
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
"RicercatoreSbadato" wrote:
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?

Aug 5 '06 #2
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');
On Sat, 05 Aug 2006 17:02:02 +0200, Muhammad Mosa <Mu**********@discussions.microsoft.comwrote:
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");


--
Happy coding!
Morten Wennevik [C# MVP]
Aug 5 '06 #3
Morten Wennevik <Mo************@hotmail.comwrote:
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);

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 5 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Doug | last post: by
4 posts views Thread by clintonG | last post: by
7 posts views Thread by WorldIsEnding | last post: by
1 post views Thread by =?Utf-8?B?UGF1bCBIYWxl?= | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.