2015-04-01 58 views
0

我想存儲在SQLite數據庫timeintervalSince1970。 如果我用這個代碼:從字符串輸出GMT的midnigth IOS的​​斯威夫特NSDate

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 

當我通過timeInSeconds到的NSDate:

let dateStore: NSDate = NSDate(timeIntervalSince1970: timeInSeconds) 

如果我打印dateStore:

println(dateStore) 

輸出「2015年3月22日23 :00:00 +0000'

timeInSeconds = 1427324400.0 - >'2015-03-22 23:00:00 +0000',但要存儲'2015-03-23 00:00:00 +0000'的區間應該是1427328000.0

我不知道如何得到它。

當我使用此代碼:

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) 

輸出的println:2015年3月22日23:00:00 +0000

任何幫助,請?

+0

http://stackoverflow.com/a/28792570/2303865 – 2015-04-01 09:13:12

+0

感謝萊昂納多,但如果當我保存myDate.timeIntervalSince1970值我使用此代碼繼續成爲1427324400.0而不是1427328000.0爲「2015年3月26日00 :00:00' – willy 2015-04-01 12:42:59

+0

NSDate對象不存儲您的時區,它存儲與您當地時間相當的時間點(UTC)。在Swift中編寫代碼時,不應該使用前綴「init」。 – 2015-04-01 16:25:34

回答

0
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 
+0

謝謝,那麼當你以秒爲單位存儲這個日期等於1,427,079,600.0,但在我當地的時間是1,427,065,200.0。在將NSTimeInterval轉換爲NSDate的兩種情況下,日期都是'23 -03-2015 00:00'。對不起,我的愚蠢:-( – willy 2015-04-01 17:19:03