2017-03-13 14 views
2

これは本当に簡単な質問ですが、私はその周りに私の頭を包んでいるようです。スウィフト - タイムゾーンが1時間/秒ずれて表示されます.FromGMTが間違っています

タイムゾーンがEDT(GMT-4)の場合、GMTの04:00は00:00ではなく23:00になるのはなぜですか?

// The offset is -4 hours 
let offsetFromGMT = Calendar.current.timeZone.secondsFromGMT()/60/60 

// 2017-03-12 04:00 
var destinationComponents = DateComponents() 
destinationComponents.timeZone = TimeZone(secondsFromGMT: 0) 
destinationComponents.year = 2017 
destinationComponents.month = 03 
destinationComponents.day = 12 
destinationComponents.hour = -offsetFromGMT // 4 hours 

// Why is this 2017-03-11 23:00 and not 2017-03-12 00:00? 
let date = Calendar.current.date(from: destinationComponents)! 
// Outputs 23 
Calendar.current.dateComponents([.hour], from: date).hour 
+0

'print(date)'は '2017-03-12 04:00:00 + 0000'と表示されます。 - あなたの地域でその日に夏時間が有効かどうかによって、あなたの地域のタイムゾーンで '2017-03-12 00:00'または' 2017-03-11 23:00'になることがあります。 - 'Calendar.current.timeZone.identifier'は何を印刷しますか? –

+0

"America/New_York"を印刷し、print(date)は2017-03-12 04:00:00 +0000を表示します。はい、なぜ夏時間は秒間に含まれていないのですか?その場合、FromGMT()? –

+0

'secondsFromGMT()'は現在のGMTオフセットです。 DSTを含む、指定された日付のGMTオフセットを返す 'secondsFromGMT(for:date)'という別の関数があります。 - あなたは実際に何を達成しようとしていますか? –

答えて

2
Calendar.current.timeZone.secondsFromGMT() 

タイムゾーンのオフセット現在 GMTです。ニューヨークの現在のタイムゾーンがEDT = GMT-4であるため、 は4時間です。あなたのdestinationComponentsdateは 4時午前グリニッジ標準時です

だから:その時点で

2017-03-12 04:00:00 +0000 

、ニューヨークのタイムゾーンは、EST = GMT-5だった、と 夏時間非活動中。したがって、あなたの現地時間帯の日付は2017-03-11 23:00です。


「secondFromGMT」を避けて、私は別の方法で進めます。

例:「2017-03-12 00:00:00」ニューヨーク時間は「2017-03-12 05:00:00」GMTです。

var srcComponents = DateComponents() 
srcComponents.timeZone = TimeZone(identifier: "America/New_York")! 
srcComponents.year = 2017 
srcComponents.month = 3 
srcComponents.day = 12 
srcComponents.hour = 0 
srcComponents.minute = 0 

let date = Calendar.current.date(from: srcComponents)! 
print(date) // 2017-03-12 05:00:00 +0000 
+0

ああ、私は夏時間がちょうど変わったことを実際には理解していませんでした。私はその年の後半になるだろうという印象を受けました。ありがとう。それはすべてを説明します。 –

+1

@ロバーツ:ようこそ! - 役に立つかもしれない別のアプローチを追加しました。 –

関連する問題