从字符串输出GMT的midnigth IOS的斯威夫特NSDate
问题描述:
我想存储在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
任何帮助,请?
答
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
http://stackoverflow.com/a/28792570/2303865 – 2015-04-01 09:13:12
感谢莱昂纳多,但如果当我保存myDate.timeIntervalSince1970值我使用此代码继续成为1427324400.0而不是1427328000.0为“2015年3月26日00 :00:00' – willy 2015-04-01 12:42:59
NSDate对象不存储您的时区,它存储与您当地时间相当的时间点(UTC)。在Swift中编写代码时,不应该使用前缀“init”。 – 2015-04-01 16:25:34