iOS NSDate() returns incorrect time

后端 未结 6 2162
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 00:10

I am trying to get current date in Swift using NSDate(). When I create breakpoint and stop application, I can see that there is 3 hours difference with devices\

6条回答
  •  悲&欢浪女
    2020-12-07 00:59

    For Swift 2.2 this function did the trick for me:

    func getCurrentLocalDate()-> NSDate {
        var now = NSDate()
        let nowComponents = NSDateComponents()
        let calendar = NSCalendar.currentCalendar()
        nowComponents.year = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: now)
        nowComponents.month = NSCalendar.currentCalendar().component(NSCalendarUnit.Month, fromDate: now)
        nowComponents.day = NSCalendar.currentCalendar().component(NSCalendarUnit.Day, fromDate: now)
        nowComponents.hour = NSCalendar.currentCalendar().component(NSCalendarUnit.Hour, fromDate: now)
        nowComponents.minute = NSCalendar.currentCalendar().component(NSCalendarUnit.Minute, fromDate: now)
        nowComponents.second = NSCalendar.currentCalendar().component(NSCalendarUnit.Second, fromDate: now)
        nowComponents.timeZone = NSTimeZone(abbreviation: "GMT")
        now = calendar.dateFromComponents(nowComponents)!
        return now
    }
    

    If you want a different timezone you can change it directly, or even better, pass it as a function parameter.

提交回复
热议问题