Formatting a TimeSpan to look like a time zone offset
Asked Answered
S

4

5

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.

Spikenard answered 20/1, 2013 at 0:54 Comment(0)
B
4

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

Boutte answered 20/1, 2013 at 1:15 Comment(1)
But if TimeSpan is negative, it will show result like -1-30. Should use Math.Abs(span.Minutes).Busyness
B
3

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).

Blanding answered 20/1, 2013 at 1:1 Comment(2)
This answer does not address the timezone offset question at all.Jerad
@WadeBaird It's been 11 years, but how does it not?Blanding
P
1

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
Pleistocene answered 13/10, 2020 at 7:30 Comment(2)
This answer does not address the timezone offset question at all.Jerad
The question was "How can I format a TimeSpan object to look like a time zone offset, like this: +0700". My answer shows how to format TimeSpan(2,30,0) to "+02:30" and also how to "-02:30". Why do you think this does not address the question?Pleistocene
B
0

I think you could use this:

String.Format("{0:zzz}", ts);
Benjy answered 20/1, 2013 at 1:1 Comment(3)
that contains a : between hours and minutes, which could be replaced to fit requirement.Geosynclinal
This outputs both colons and seconds which you'd have to then remove.Blanding
This code gives runtime error: "System.FormatException: 'Input string was not in a correct format.'Pleistocene

© 2022 - 2024 — McMap. All rights reserved.