Formatting a TimeSpan to look like a time zone off

2019-07-21 01:01发布

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.

3条回答
唯我独甜
2楼-- · 2019-07-21 01:32

I think you could use this:

String.Format("{0:zzz}", ts);
查看更多
别忘想泡老子
3楼-- · 2019-07-21 01:47

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

查看更多
做个烂人
4楼-- · 2019-07-21 01:54

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

查看更多
登录 后发表回答