将 TimeSpan 格式化为时区偏移量 [英] Formatting a TimeSpan to look like a time zone offset

查看:30
本文介绍了将 TimeSpan 格式化为时区偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 TimeSpan 对象格式化为时区偏移量,如下所示:

How can I format a TimeSpan object to look like a time zone offset, like this:

+0700

-0600

我正在使用 GetUtcOffset 获得一个偏移量,它的工作原理,但它返回一个 TimeSpan 对象.

I'm using GetUtcOffset to get an offset, and its working, but its returning a TimeSpan object.

推荐答案

如果您使用的是 .Net 4.0 或更高版本,您可以使用 hh<在时间跨度上使用 ToString 方法/code> 和 mm 说明符(不确定它是否会显示 + 和 - 符号):

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"));

如果没有,您可以只格式化 HoursMinutes 属性以及一些条件格式以始终显示 + 和 - 符号:

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

TimeSpan 格式字符串参考:http://msdn.microsoft.com/en-gb/library/ee372287.aspx

Reference for TimeSpan format strings: http://msdn.microsoft.com/en-gb/library/ee372287.aspx

数字格式字符串及其条件格式的参考:http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Reference for numeric format strings and conditional formatting of them: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

这篇关于将 TimeSpan 格式化为时区偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆