Created
February 2, 2020 15:22
-
-
Save PetreVane/fe3951e7e954a911ead3386351fac201 to your computer and use it in GitHub Desktop.
These 2 extensions convert a String to Date, and back to String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Date { | |
//2 | |
func convertToMonthYearFormat() -> String { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "MMM yyyy" | |
return dateFormatter.string(from: self) | |
} | |
} | |
extension String { | |
//1 | |
func convertToDate() -> Date? { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" | |
dateFormatter.locale = Locale(identifier: "en_US_POSIX") | |
dateFormatter.timeZone = .current | |
return dateFormatter.date(from: self) | |
} | |
//3 | |
func convertToDisplayFormat() -> String { | |
guard let date = self.convertToDate() else { return "N/A" } | |
return date.convertToMonthYearFormat() | |
} | |
} | |
// Using it: | |
self.dateLabel.text = "On GitHub since \(user.createdAt.convertToDisplayFormat())" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yo thanks so much!