In objective-c, the following code results in the UTC date time information using the date
API.
NSDate *currentUTCDate = [NSDate date]
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"*
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()
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
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");