问题
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