TimeSpace.Parse() usage

S

SpaceMarine

hello,

ive read the MSDN docs on using the TimeSpace.Pars() method to format
timespans, however i found their examples unclear.

currently i am doing this:

Dim startTime As DateTime = DateTime.Now
...
Dim endTime As DateTime = DateTime.Now
Dim elapsedTime As TimeSpan = endTime.Subtract(startTime)

writer.WriteLine("Time difference: {0} hours, {1} minutes, {2}
seconds.", elapsedTime.Hours, elapsedTime.Minutes,
elapsedTime.Seconds)

....but i get the impression there is a much simpler string formatter
technique. ive tried this, to no effect:

writer.WriteLine("Time difference: {0:hh:mm:ss}", elapsedTime)


anybody know the magic?

thanks!
sm
 
P

Peter Duniho

SpaceMarine said:
[...]
....but i get the impression there is a much simpler string formatter
technique. ive tried this, to no effect:

writer.WriteLine("Time difference: {0:hh:mm:ss}", elapsedTime)


anybody know the magic?

There's no magic. The TimeSpan class has no formatting options, so you
need to break it apart as in the example you found, if you are going to
use the TimeSpan directly.

One alternative is to convert the TimeSpan back to a DateTime, which of
course does have formatting options like you're trying to use:

writer.WriteLine("Time difference: {0:hh:mm:ss}",
new DateTime() + elapsedTime);

Sort of hacky, but it works.

Pete
 
S

SpaceMarine

SpaceMarine said:
[...]
....but i get the impression there is a much simpler string formatter
technique. ive tried this, to no effect:
writer.WriteLine("Time difference: {0:hh:mm:ss}", elapsedTime)
anybody know the magic?

There's no magic. The TimeSpan class has no formatting options

bummer. i had thought from all that jibjab on msdn's TimeSpan.Parse()
that there would be something like it.

http://msdn2.microsoft.com/en-us/library/system.timespan.parse(vs.71).aspx


thanks
sm
 
P

Peter Duniho

SpaceMarine said:
bummer. i had thought from all that jibjab on msdn's TimeSpan.Parse()
that there would be something like it.

Yes. You'd think that you would be able to specify string formatting
for converting a TimeSpan to a string that's similar to the description
they offer for parsing from a string.

But as far as I know, they don't. And I have looked pretty thoroughly.
The TimeSpan.ToString() method doesn't even offer an overload with a
formatting string parameter.

Pete
 

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