c#解析UTC datetime [英] c# Parsing UTC datetime
问题描述
我正在尝试解析11/23/2011 23:59:59 UTC +0800 as ac#datetime对象,但尝试使用标准的datetime解析方法,甚至datetime精确解析我得到无效的日期。
I am trying to parse 11/23/2011 23:59:59 UTC +0800 as a c# datetime object but trying the standard datetime parse method or even the datetime exact parse I get invalid date.
任何想法?
推荐答案
我建议您解析为 DateTimeOffset
而不是 DateTime
,时,MSDN中建议使用rel =noreferrer>
I would suggest you parse to a DateTimeOffset
instead of a DateTime
, as recommended in MSDN when using a time zone offset specifier in the format string:
using System;
using System.Globalization;
class Test
{
static void Main(string[] args)
{
string text = "11/23/2011 23:59:59 UTC +0800";
string pattern = "MM/dd/yyyy HH:mm:ss 'UTC' zzz";
DateTimeOffset dto = DateTimeOffset.ParseExact
(text, pattern, CultureInfo.InvariantCulture);
Console.WriteLine(dto);
}
}
然后,您可以将其转换为 DateTime
值,如果你想要的,但没有像$ DateTime
的偏移量为8小时 - 一个 DateTime
被视为通用的,本地的或未指定的,无法存储特定的偏移量。
You can then convert that to a DateTime
value in UTC if you want, but there's no such thing as "a DateTime
with an offset of 8 hours" - a DateTime
is either regarded as universal, local or unspecified, with nowhere for a specific offset to be stored.
DateTime
是一个以各种方式好奇的类型,并且可能导致不必要的开发者出现问题。
DateTime
is a curious type in various ways, and can cause problems for the unwary developer.
这篇关于c#解析UTC datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!