Search code examples
nsdatenscalendar

IOS Swift NSDate from String output GMT midnigth


I want to store in a sqlite database timeintervalSince1970. If I use this code:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
var initDate: NSDate = dateFormatter.dateFromString("23-03-2015 00:00")!
let timeInSeconds = initDate.timeintervalSince1970 // 1,427,324,400.0

When I pass timeInSeconds to NSDate:

let dateStore: NSDate = NSDate(timeIntervalSince1970: timeInSeconds)

If I print dateStore:

println(dateStore)

Output '2015-03-22 23:00:00 +0000'

timeInSeconds = 1427324400.0 -> '2015-03-22 23:00:00 +0000', but to store '2015-03-23 00:00:00 +0000' the interval should be 1427328000.0

I do not know how to get it.

When I use this code:

let cal2: NSCalendar = NSCalendar.currentCalendar()
cal2.timeZone = NSTimeZone(name: "Europe/Madrid")!

var timeZoneComps: NSDateComponents = NSDateComponents()

timeZoneComps.day = 23
timeZoneComps.month = 3
timeZoneComps.year = 2015
timeZoneComps.hour = 0
timeZoneComps.minute = 0
timeZoneComps.second = 0

var date1: NSDate = cal2.dateFromComponents(timeZoneComps)!
println(date1)

Output println: 2015-03-22 23:00:00 +0000

Any help, please?


Solution

  • let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
    let myDateMidnightLocalTime = dateFormatter.dateFromString("23-03-2015 00:00")!  // Mar 23, 2015, 12:00 AM
    let timeInSeconds = myDateMidnightLocalTime.timeIntervalSince1970                // 1,427,079,600.0  
    let dateStored = NSDate(timeIntervalSince1970: timeInSeconds)                    // Mar 23, 2015, 12:00 AM  matches
    dateStored.timeIntervalSince1970                                                 // 1,427,079,600.0  matches