Swift - Get local date and time

前端 未结 10 661
挽巷
挽巷 2020-12-17 08:51

How can I get local date and time in Swift?

let last_login = String(NSDate.date())
10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 09:32

    In case you want to get a Date object and not a string representation you can use the following snippet:

    extension Date {
        func localDate() -> Date {
            let nowUTC = Date()
            let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC))
            guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {return Date()}
    
            return localDate
        }
    }
    

    Use it like this:

    let now = Date().localDate()
    

提交回复
热议问题