将 TimeSpan 格式化为时区偏移量

编程入门 行业动态 更新时间:2024-10-28 15:30:35
本文介绍了将 TimeSpan 格式化为时区偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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"));

如果没有,您可以只格式化 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/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:关键词]

本文发布于:2023-04-30 10:24:13,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时区   格式   偏移量   TimeSpan

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!