Get UTC time and local time from NSDate object

前端 未结 10 1004
夕颜
夕颜 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:42

    NSDate is a specific point in time without a time zone. Think of it as the number of seconds that have passed since a reference date. How many seconds have passed in one time zone vs. another since a particular reference date? The answer is the same.

    Depending on how you output that date (including looking at the debugger), you may get an answer in a different time zone.

    If they ran at the same moment, the values of these are the same. They're both the number of seconds since the reference date, which may be formatted on output to UTC or local time. Within the date variable, they're both UTC.

    Objective-C:

    NSDate *UTCDate = [NSDate date]
    

    Swift:

    let UTCDate = NSDate.date()
    

    To explain this, we can use a NSDateFormatter in a playground:

    import UIKit
    
    let date = NSDate.date()
        // "Jul 23, 2014, 11:01 AM" <-- looks local without seconds. But:
    
    var formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    let defaultTimeZoneStr = formatter.stringFromDate(date)
        // "2014-07-23 11:01:35 -0700" <-- same date, local, but with seconds
    formatter.timeZone = NSTimeZone(abbreviation: "UTC")
    let utcTimeZoneStr = formatter.stringFromDate(date)
        // "2014-07-23 18:01:41 +0000" <-- same date, now in UTC
    

    The date output varies, but the date is constant. This is exactly what you're saying. There's no such thing as a local NSDate.

    As for how to get microseconds out, you can use this (put it at the bottom of the same playground):

    let seconds = date.timeIntervalSince1970
    let microseconds = Int(seconds * 1000) % 1000 // chops off seconds
    

    To compare two dates, you can use date.compare(otherDate).

提交回复
热议问题