Get UTC time and local time from NSDate object

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

    let date = Date() 
    print(date) // printed date is UTC 
    

    If you are using playground, use a print statement to check the time. Playground shows local time until you print it. Do not depend on the right side panel of playground.

    This code gives date in UTC. If you need the local time, you should call the following extension with timezone as Timezone.current

     extension Date {
    
       var currentUTCTimeZoneDate: String {
            let formatter = DateFormatter()
            formatter.timeZone = TimeZone(identifier: "UTC")
            formatter.amSymbol = "AM"
            formatter.pmSymbol = "PM"
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
            return formatter.string(from: self)
        }
    }
    

    For UTC time, use it like: Date().currentUTCTimeZoneDate

提交回复
热议问题