问题描述
我正在使用一种协议,该协议在指定日期时间信息时可以选择包含时区偏移量.我的代码是用 C# 编写的,我们使用的是 4.0 .NET 运行时.我看到有一个 格式化选项 "zzz" 用于包含时区信息但是,在解析和格式化时,冒号 (:) 似乎是固定的.例如,使用自定义格式字符串 (yyyyMMddHHmmsszzz) 格式化的日期时间可能显示为:
I'm working with a protocol that may optionally include a time zone offset when specifying datetime information. My code is written in C# and we are using the 4.0 .NET runtime. I see that there is a formatting option "zzz" for including timezone information when parsing and formatting, however, it appears that the colon (:) is fixed. For instance, a Datetime formatted with the custom format string (yyyyMMddHHmmsszzz) might appear as:
20100309101530-05:00
我正在使用的协议在时区偏移中不包含冒号.该协议将格式化日期时间,并期望它们被格式化为:
The protocol I am working with does not include the colon in the timezone offset. This protocol will format datetimes, and expect them to be formatted as:
20100309101530-0500
在使用包含时区偏移的自定义格式化程序解析或格式化日期时间时,有没有办法控制冒号的外观?
Is there a way to control the appearance of the colon when parsing or formatting datetime with a custom formatter that includes the timezone offset?
推荐答案
看起来好像没有内置任何东西(你可以使用 zz
,但这省去了分钟).
Doesn't look like there is anything built-in (you can use zz
, but that leaves out the minutes).
您可以通过实例化 DateTimeFormatInfo
,将 TimeSeparator
设置为 string.Empty
并在调用 DateTime.ToString
时将其用作 IFormatProvider
(并明确调用(如果尚未调用).
You can roll your own by instantiating a DateTimeFormatInfo
, setting TimeSeparator
to string.Empty
and using that as the IFormatProvider
when calling DateTime.ToString
(and make the call explicit, if it is not already).
但坦率地说,使用 Replace
来从默认返回值中删除不需要的 :
要容易得多.
But frankly, using Replace
to remove the unwanted :
from the default return value is so much easier.
这篇关于解析/格式化日期时间时如何控制时区偏移中“:"的外观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!