[更新:格式说明符与格式字符串不同;格式说明符是自定义格式字符串的一部分,其中格式字符串是“库存”并且不提供自定义。我的问题是说明符不是格式]
我一直在尝试使用使用“zzz”格式说明符的格式字符串执行往返日期时间转换,我知道它与本地时间绑定。因此,如果我尝试使用 UTC 日期时间往返,它会抛出 DateTimeInvalidLocalFormat 异常,它应该使用以下文本:
UTC 日期时间正在转换为仅适用于当地时间的格式的文本。这可能在使用“z”格式说明符调用 DateTime.ToString 时发生,该说明符将在输出中包含本地时区偏移量。在这种情况下,要么使用指定 UTC 时间的“Z”格式说明符,要么使用“o”格式字符串,这是在文本中保存 DateTime 的推荐方法。当传递要由 XmlConvert 或 DataSet 序列化的 DateTime 时,也会发生这种情况。如果使用 XmlConvert.ToString,则传入 XmlDateTimeSerializationMode.RoundtripKind 以正确序列化。如果使用 DataSet,请将 DataColumn 对象上的 DateTimeMode 设置为 DataSetDateTime.Utc。
根据这个建议,我需要做的就是让我的代码工作是用 'ZZZ' 替换 'zzz' 这样我就可以采用 UTC 格式。问题是,在文档中的任何地方都找不到“Z”,我尝试的任何“Z”格式组合,即“Z”、“ZZ”、“ZZZ”,总是只是将 DateTime 实例转换为那些 Z 被视为文字.
是否有人忘记在没有告诉异常消息作者的情况下实现“Z”,或者我错过了如何在没有黑客攻击的情况下用“+0000”替换有效的本地时间偏移?
代码示例:
// This is the format with 'zzzzz' representing local time offset
const string format = "ddd MMM dd HH:mm:ss zzzzz yyyy";
// create a UTC time
const string expected = "Fri Dec 19 17:24:18 +0000 2008";
var time = new DateTime(2008, 12, 19, 17, 24, 18, 0, DateTimeKind.Utc);
// If you're using a debugger this will rightfully throw an exception
// with .NET 3.5 SP1 because 'z' is for local time only; however, the exception
// asks me to use the 'Z' specifier for UTC times, but it doesn't exist, so it
// just spits out 'Z' as a literal.
var actual = time.ToString(format, CultureInfo.InvariantCulture);
Assert.AreEqual(expected, actual);