问题
How can I format a TimeSpan
object to look like a time zone offset, like this:
+0700
or
-0600
I'm using GetUtcOffset to get an offset, and its working, but its returning a TimeSpan object.
回答1:
If you're using .Net 4.0 or above, you can use the ToString
method on timespan with the hh
and mm
specifier (not sure if it will display the + and - signs though):
TimeSpan span = new TimeSpan(7, 0, 0);
Console.WriteLine(span.ToString("hhmm"));
If not, you can just format the Hours
and Minutes
properties along with some conditional formatting to always display the + and - signs:
TimeSpan span = new TimeSpan(7, 0, 0);
Console.WriteLine("{0:+00;-00}{1:00}", span.Hours, span.Minutes);
Reference for TimeSpan format strings: http://msdn.microsoft.com/en-gb/library/ee372287.aspx
Reference for numeric format strings and conditional formatting of them: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
回答2:
Try something like:
var timespan = new TimeSpan(-5,0,0); // EST
var offset = String.Format("{0}{1:00}{2:00}",(timespan.Hours >= 0 ? "+" : String.Empty),timespan.Hours,timespan.Minutes);
I add the + when the number is non-negative (for negative numbers a - should be output).
回答3:
I think you could use this:
String.Format("{0:zzz}", ts);
来源:https://stackoverflow.com/questions/14420618/formatting-a-timespan-to-look-like-a-time-zone-offset