Get UTC time and local time from NSDate object

前端 未结 10 1022
夕颜
夕颜 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: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");
    

提交回复
热议问题