Get UTC time and local time from NSDate object

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

    I found an easier way to get UTC in Swift4. Put this code in playground

    let date = Date() 
    *//"Mar 15, 2018 at 4:01 PM"*
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    
    let newDate = dateFormatter.string(from: date) 
    *//"2018-03-15 21:05:04 +0000"*
    
    0 讨论(0)
  • 2020-11-28 23:46

    Swift 3

    You can get Date based on your current timezone from UTC

    extension Date {
        func currentTimeZoneDate() -> String {
            let dtf = DateFormatter()
            dtf.timeZone = TimeZone.current
            dtf.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
            return dtf.string(from: self)
        }
    }
    

    Call like this:

    Date().currentTimeZoneDate()
    
    0 讨论(0)
  • 2020-11-28 23:50

    My Xcode Version 6.1.1 (6A2008a)

    In playground, test like this:

    // I'm in East Timezone 8
    let x = NSDate() //Output:"Dec 29, 2014, 11:37 AM"
    let y = NSDate.init() //Output:"Dec 29, 2014, 11:37 AM"
    println(x) //Output:"2014-12-29 03:37:24 +0000"
    
    
    // seconds since 2001
    x.hash //Output:441,517,044
    x.hashValue //Output:441,517,044
    x.timeIntervalSinceReferenceDate //Output:441,517,044.875367
    
    // seconds since 1970
    x.timeIntervalSince1970 //Output:1,419,824,244.87537
    
    0 讨论(0)
  • 2020-11-28 23:54

    In addition to other answers, you can write an extension for Date class to get formatted Data in specific TimeZone to make it as utility function for future use. Like

     extension Date {
    
     func dateInTimeZone(timeZoneIdentifier: String, dateFormat: String) -> String  {
     let dtf = DateFormatter()
     dtf.timeZone = TimeZone(identifier: timeZoneIdentifier)
     dtf.dateFormat = dateFormat
    
     return dtf.string(from: self)
     }
    }
    

    Now you can call it like

     Date().dateInTimeZone(timeZoneIdentifier: "UTC", dateFormat: "yyyy-MM-dd HH:mm:ss");
    
    0 讨论(0)
提交回复
热议问题