I have a string Fri, 16 Aug 2019 07:04:12 +0000
and I want to convert it to german string representation 16.8.2019 07:04:12
How can I do that in Swift 4?
Thanks a lot
Usually we use DateFormatter to parse and format dates. Try this code.
let inputDateString = "Fri, 16 Aug 2019 07:04:12 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let inputDate = formatter.date(from: inputDateString)
let germanDateFormatter = DateFormatter()
germanDateFormatter.dateFormat = "d.M.yyyy HH:mm:ss"
germanDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
if let date = inputDate {
let result = germanDateFormatter.string(from: date)
print(result) //16.8.2019 07:04:12
}
Also you can use this service to find common date formats https://nsdateformatter.com
As suggested in comments you can use Locale to format the date according to the user Locale. But you will get a bit another format then you need.
let inputDateString = "Fri, 16 Aug 2019 07:04:12 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let inputDate = formatter.date(from: inputDateString)
let germanDateFormatter = DateFormatter()
germanDateFormatter.locale = .init(identifier: "de")
germanDateFormatter.dateStyle = .short
germanDateFormatter.timeStyle = .medium
germanDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
if let date = inputDate {
let result = germanDateFormatter.string(from: date)
print(result) //16.08.19, 07:04:12
}
de
and let the system format it for you, or generate the formatting string from a pattern. Setting time zone for the formatter in this case is probably also wrong and you have to set POSIX locale for the parser.
Date
, which can you find a lot of times on SO. 2. formatDate
usingDateFormatter
, setting a specific locale. Nothing else is needed.