Reputation: 31
I've been trying to take a date saved in the format of "Thu Nov 12 2020 07:00:00 GMT+0000 (Greenwich Mean Time)" and convert it into the format of "MMM d, yyyy", however I am unsuccessful in doing so.
import Foundation
extension String {
// Example date read in from database.
// "Thu Nov 12 2020 07:00:00 GMT+0000 (Greenwich Mean Time)"
func convertToDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
dateFormatter.locale = Locale(identifier: "en_US_POSSIX")
dateFormatter.timeZone = .current
return dateFormatter.date(from: self)
}
func convertToDisplayFormat() -> String {
guard let date = self.convertToDate() else { return "N/A"}
return date.convertToMonthDayTimeFormat()
}
}
import Foundation
extension Date {
func convertToMonthDayTimeFormat() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy"
print(dateFormatter.string(from: self))
return dateFormatter.string(from: self)
}
}
And then in the file in which I read in the data the code is
cell.appointmentTime?.text = "\(tableData.date!.convertToDisplayFormat())"
Upvotes: 1
Views: 577
Reputation: 236360
You should always set your dateFormat locale to "en_US_POSIX"
before setting the dateFormat. Btw it looks like that your date string you are reading from database is always in UTC format, if that is the case you should set your dateFormatter timezone to zero secondsFromGMT and escape your date string timezone:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSSIX")
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT+0000 (Greenwich Mean Time)'"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.date(from: "Thu Nov 12 2020 07:00:00 GMT+0000 (Greenwich Mean Time)")
You should also create a static date formatter to avoid creating a new one every time you call this method:
extension Formatter {
static let customDate: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSSIX")
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT+0000 (Greenwich Mean Time)'"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return dateFormatter
}()
static let yyyyMMMd: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("yyyyMMMd")
return dateFormatter
}()
}
extension String {
func convertToDate() -> Date? {
Formatter.customDate.date(from: self)
}
func convertToDisplayFormat() -> String {
convertToDate()?.convertToMonthDayTimeFormat() ?? "N/A"
}
}
extension Date {
func convertToMonthDayTimeFormat() -> String {
Formatter.yyyyMMMd.string(from: self)
}
}
Playground testing:
"Thu Nov 12 2020 07:00:00 GMT+0000 (Greenwich Mean Time)".convertToDisplayFormat() // "Nov 12, 2020"
Upvotes: 1