问题描述
限时送ChatGPT账号..如何将 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"));
如果没有,您可以只格式化 Hours
和 Minutes
属性以及一些条件格式以始终显示 + 和 - 符号:
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/en-gb/library/ee372287.aspx
Reference for TimeSpan format strings: http://msdn.microsoft/en-gb/library/ee372287.aspx
数字格式字符串及其条件格式的参考:http://msdn.microsoft/en-us/library/0c899ak8.aspx
Reference for numeric format strings and conditional formatting of them: http://msdn.microsoft/en-us/library/0c899ak8.aspx
这篇关于将 TimeSpan 格式化为时区偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论