Custom Formatter with String.Format

  • Thread starter Thread starter clintonG
  • Start date Start date
C

clintonG

TimeSpan utcOffset = localZone.GetUtcOffset(DateTime.Now);
MessageLabel.Text = utcOffset.ToString( ); // returns -06:00:00

Instead of -06:00:00 I want -06:00.
Apparently the custom formatter should be 0:zzz but I can't figure out the
correct String.Format grammar to get the desired result.
Can you?

<%= Clinton Gallagher
 
Clinton,

I did some searching for "TimeSpan format" on the .NET newsgroups, and
found some other messages asking similar questions. It looks like
TimeSpan is not as nicely formattable as other classes and structs in
..NET (like DateTime). One suggestion to get what you were asking for
is something like:

string formatedTimeSpan=String.Format("{0:00}:{1:00}", utcOffset.Hours,
utcOffset.Minutes);

See
http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/msg/e5a8dcf28516873f

-- Tim Scott
http://geekswithblogs.net/tscott
 
If you're just formatting your time for display you could do something like

DateTime displayTime = DateTime.MinValue + time;
Console.WriteLine(displayTime.ToString("-HH:mm");

HTH
 
Back
Top