要解析字符串,因为你只有日期和时间,并且知道字符串的特定格式,所以请按照以下步骤进行:
DateTime dt = DateTime.ParseExact("201503131557", "yyyyMMddHHmm", CultureInfo.InvariantCulture);
生成的值将其
Kind
属性设置为
DateTimeKind.Unspecified
(不是本地时间,正如您所认为的那样)。这是可以预料的,因为您没有提供有关此时间戳与UTC或本地时间的关系的任何信息。
您说该值表示中央标准时间中的时间。 您将需要一个理解该时区的
TimeZoneInfo
对象。
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
请注意,此标识符表示美国观察到的中央时间,包括CST或CDT,具体取决于给定值的有效性(尽管其名称中有“标准”一词)。还要注意,它仅在Windows操作系统上有效。如果您想在其他操作系统上使用.NET Core,则需要传递IANA标识符“America/Chicago”(或使用我的
TimeZoneConverter库在任何平台上使用任一标识符)。
下一步是确定您想要对此值执行什么操作。您可以对其进行几种不同的操作:
If you want to convert it to the equivalent UTC value, represented as a DateTime
, then you can do this:
DateTime utc = TimeZoneInfo.ConvertTimeToUtc(dt, tz)
If you want a DateTimeOffset
representation which holds the input you gave and the offset from UTC as it related to US Central Time, then you can do this:
TimeSpan offset = tz.GetUtcOffset(dt);
DateTimeOffset dto = new DateTimeOffset(dt, offset);
Keep in mind that it's possible for the input time is invalid or ambiguous if it falls near a DST transition. The GetUtcOffset
method will return the standard offset in such cases. If you want different behavior, you have more code to write (out of scope for this post).
There are other things you might do, all of which are provided by the TimeZoneInfo
class.
请注意,“Azure PaaS”可能指的是几个不同的东西,虽然在Azure App Service中有一个名为
WEBSITE_TIME_ZONE
的设置,但我不建议您依赖它。将其视为最后的手段,仅在您无法控制代码时使用。在大多数情况下,最好编写您的代码,使其永远不依赖于运行系统的时区设置。这意味着永远不要调用
DateTime.Now
、
TimeZoneInfo.Local
、
DateTime.ToLocalTime
甚至
DateTime.ToUniversalTime
(因为它从本地时区转换),等等。相反,依赖于明确使用UTC或特定时区或偏移量的方法。然后您就不需要关心应用程序托管的位置。
最后,请了解
DateTime
类型和
DateTimeOffset
类型都没有理解值与特定时区相关联的能力。为此,您需要编写自己的类,或查看
Noda Time库,其
ZonedDateTime
类提供了这样的功能。