解析/格式化日期时间时如何控制时区偏移中“:"的外观

How to control appearance of #39;:#39; in time zone offset when parsing/formatting Datetime(解析/格式化日期时间时如何控制时区偏移中“:的外观)
本文介绍了解析/格式化日期时间时如何控制时区偏移中“:"的外观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一种协议,该协议在指定日期时间信息时可以选择包含时区偏移量.我的代码是用 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.

这篇关于解析/格式化日期时间时如何控制时区偏移中“:"的外观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)