简体   繁体   English

将没有时区信息的DateTime解析为特定的时区

[英]Parse DateTime without Timezone information into specific Timezone

This is a follow on from a question answered yesterday.. 这是昨天回答的问题的后续内容。

Convert 12hr Time String to DateTime object 将12hr时间字符串转换为DateTime对象

Those times in the xml feed are EST (who does that?) but our timezone is BST. xml feed中的时间是EST(谁这样做的)?但是我们的时区是BST。

so 10:30PM is 02:30AM UTC or 03:30AM BST 所以10:30 PM是UTC的02:30 AM或BST的03:30 AM

However, TryParseExact yields 10:30PM in local time (as to be expected given that there is not timezone information) 但是,TryParseExact在本地时间产生10:30 PM(由于没有时区信息,因此可以预期)

So the question; 所以这个问题; how can I parse that time as 02:30AM UTC rather than 10:30PM BST? 如何将时间解析为世界标准时间02:30 AM而不是BST 10:30 PM?

However, TryParseExact yields 10:30PM in local time 但是,TryParseExact在当地时间产生10:30 PM

No, it doesn't. 不,不是。 Not unless you tell it to. 除非您告知,否则不会。 By default, and unless there's any indication of the offset in the pattern, the parse methods will return DateTime values with a Kind of Unspecified - which is entirely appropriate as no information has been specified. 默认情况下,除非在模式中有任何偏移指示,否则解析方法将返回带有Unspecified KindDateTime值-这完全合适,因为未指定任何信息。 If you just convert it to a string, it will assume it's actually a local time, but that's not what the value itself says. 如果仅将其转换为字符串,它将假定它实际上是本地时间,但这不是值本身所说明的。 You need to understand the three kinds of DateTime - it's a broken model IMO , but that's what we've got in the BCL. 您需要了解三种DateTime这是IMO损坏模型 ,但这就是BCL中提供的内容。

You can pass that to the appropriate TimeZoneInfo to apply a specific time zone and get an appropriate DateTimeOffset , although it's then up to you to remember the actual time zone involved. 您可以将其传递给适当的TimeZoneInfo以应用特定的时区并获取适当的DateTimeOffset ,尽管这取决于您记住实际的时区。 (An offset isn't the same as a time zone.) (偏移量与时区不同。)

Alternatively, you could use my Noda Time project, which differentiates between the different logical types rather more clearly. 另外,您可以使用我的Noda Time项目,该项目可以更清楚地区分不同的逻辑类型。 You'd parse as a LocalTime , then decide which LocalDate to join that with in order to produce LocalDateTime , which you could then convert to a ZonedDateTime using the "America/Los_Angeles" time zone (or the Windows equivalent; the choice is yours). 您可以将其解析为LocalTime ,然后决定与哪个LocalDate一起加入以生成LocalDateTime ,然后可以使用“ America / Los_Angeles”时区(或Windows等效项;您可以根据自己的选择)将其转换为ZonedDateTime 。 。 In performing that conversion, you'd specify what you'd want to happen if the given local time was invalid or ambiguous due to daylight saving transitions. 在执行该转换时,您将指定如果由于夏令时转换导致给定的本地时间无效或不明确的情况,您希望发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM