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.
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.
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
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).
This code:
var timeSpan = new TimeSpan(2, 30, 0);
Console.WriteLine(new DateTimeOffset(2000, 1, 1, 1, 1, 1, timeSpan).ToString("zzz"));
Console.WriteLine(new DateTimeOffset(2000, 1, 1, 1, 1, 1, -timeSpan).ToString("zzz"));
outputs:
+02:30
-02:30
I think you could use this:
String.Format("{0:zzz}", ts);
© 2022 - 2024 — McMap. All rights reserved.
TimeSpan
is negative, it will show result like-1-30
. Should useMath.Abs(span.Minutes)
. – Busyness