Icemanind
Icemanind

Reputation: 48726

Formatting a TimeSpan to look like a time zone offset

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.

Upvotes: 5

Views: 3820

Answers (4)

Vlad Rudenko
Vlad Rudenko

Reputation: 2839

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

Upvotes: 1

Lloyd
Lloyd

Reputation: 29668

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

Upvotes: 3

Sean Airey
Sean Airey

Reputation: 6372

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

Upvotes: 4

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

I think you could use this:

String.Format("{0:zzz}", ts);

Upvotes: 0

Related Questions