如何控制外观“:”在时区在解析时/格式化日期时间偏移时区、外观、日期、时间

2023-09-04 09:16:02 作者:性感的猪蹄

我正与一个协议,它可以选择性地包括指定的日期时间信息,当一个时区偏移量。我的code是用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 和使用,作为的IFormatProvider 打电话时则DateTime.ToString (和拨打电话明确,如果没有的话)。

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

但坦率地说,使用 替换 删除不需要的从默认返回值是如此容易得多

But frankly, using Replace to remove the unwanted : from the default return value is so much easier.