Date comparison or timezone not set properly

为君一笑 提交于 2019-12-24 12:46:08

问题


I'm trying to do a simple comparison of dates with the intent of moving to another array index based on the day.

Though vastly more efficient than the code I was using, the following (Unable to parse a date) doesn't preserve the timezone offset:

let noaaDate = "2014-08-22T15:00:00-04:00"
let format="yyyy-MM-dd'T'HH:mm:ssZ"

var dateFmt = NSDateFormatter()
dateFmt.dateFormat = format
let newreadableDate = dateFmt.dateFromString(noaaDate)
println(newreadableDate)

Output:

Optional(2014-08-22 19:00:00 +0000)

When I add the following:

dateFmt.timeZone = NSTimeZone.localTimeZone()  // I've even tried defaultTimeZone

the output is the same. Where this seems to become an issue is later on when I'm doing the following:

// FYI:  parseNOAADateTime is that code above        
var earliestTimeNS = parseNOAADateTime(earliestTime!) 
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitDay, fromDate: earliestTimeNS)
let dayZero = components.day

// stuff, like starting a loop
let tempDateTimeString = "2014-08-31T01:00:00-04:00"
let thisDateTime = parseNOAADateTime(tempDateTimeString!)
let tempDateTimeComponents = calendar.components(.CalendarUnitDay, fromDate: thisDateTime)
let forecastIndex = tempDateTimeComponents.day - dayZero

Now, forecastIndex SHOULD be 6 because tempDateTimeComponents.day SHOULD be 31. However, they're 5 and 30, respectively, meaning four hour's worth of data is ending up with the previous day's data.

Where am I messing up?

Thanks

来源:https://stackoverflow.com/questions/25489969/date-comparison-or-timezone-not-set-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!