iOS NSDate() returns incorrect time

后端 未结 6 2154
隐瞒了意图╮
隐瞒了意图╮ 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:35

    This func returns Now in a current time zone.

    func convertDate(date:Date) -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        var comp = DateComponents()
        let calendar = Calendar.current
        comp.year = Calendar.current.component(.year, from: date)
        comp.month = Calendar.current.component(.month, from: date)
        comp.day = Calendar.current.component(.day, from: date)
        comp.hour = Calendar.current.component(.hour, from: date)
        comp.minute = Calendar.current.component(.minute, from: date)
        comp.second = Calendar.current.component(.second, from: date)
        comp.timeZone = TimeZone(abbreviation: "GMT")
        var dateFromCalendar = Date()
        if let calendarDate = calendar.date(from: comp) {
            dateFromCalendar = calendarDate
        }
        return dateFromCalendar
    }
    

    To use:

        let now = Date()
        let convertedDate = convertDate(date: now)
    

提交回复
热议问题