Reputation: 1691
So currently I have this extension for Formatter which returns : 16/10/17 08:37:50 PM GMT but I need 16/10/17 08:37:50 PM UTC with UTC as appended to the nsdate. How can I achieve that?
Following is my code:
extension Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(abbreviation:"UTC") as TimeZone!
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
formatter.dateFormat = "dd/MM/yy hh:mm:ss a zzz"
return formatter
}()
}
Upvotes: 0
Views: 94
Reputation: 131408
Just change your date formatter to use 'UTC'
in place of zzz
in your format string:
formatter.dateFormat = "dd/MM/yy hh:mm:ss a 'UTC'"
You need to put string literals like UTC
in single quotes so they are not interpreted as format characters.
Note that the above will only work correctly if you set the date format to the UTC time zone. If you set it to some other time zone then the output string will still end with UTC
, which will be wrong.
Upvotes: 2
Reputation: 2685
Here i'm changing current date to save same hour and date but only time zone changes. Try if this works for you
var now: Date {
let formatter = DateFormatter()
formatter.dateFormat = Const.dateFormat
formatter.timeZone = TimeZone.current
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss a zzz"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let str = dateFormatter.string(from: date)
return formatter.date(from: str)
}
Upvotes: 0