Get UTC time and local time from NSDate object

前端 未结 10 1000
夕颜
夕颜 2020-11-28 23:17

In objective-c, the following code results in the UTC date time information using the date API.

NSDate *currentUTCDate = [NSDate date]
         


        
10条回答
  •  自闭症患者
    2020-11-28 23:36

    Xcode 9 • Swift 4 (also works Swift 3.x)

    extension Formatter {
        // create static date formatters for your date representations
        static let preciseLocalTime: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = "HH:mm:ss.SSS"
            return formatter
        }()
        static let preciseGMTTime: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.timeZone = TimeZone(secondsFromGMT: 0)
            formatter.dateFormat = "HH:mm:ss.SSS"
            return formatter
        }()
    }
    

    extension Date {
        // you can create a read-only computed property to return just the nanoseconds from your date time
        var nanosecond: Int { return Calendar.current.component(.nanosecond,  from: self)   }
        // the same for your local time
        var preciseLocalTime: String {
            return Formatter.preciseLocalTime.string(for: self) ?? ""
        }
        // or GMT time
        var preciseGMTTime: String {
            return Formatter.preciseGMTTime.string(for: self) ?? ""
        }
    }
    

    Playground testing

    Date().preciseLocalTime // "09:13:17.385"  GMT-3
    Date().preciseGMTTime   // "12:13:17.386"  GMT
    Date().nanosecond       // 386268973
    

    This might help you also formatting your dates:

    enter image description here

提交回复
热议问题