Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Created February 2, 2020 15:22
Show Gist options
  • Save PetreVane/fe3951e7e954a911ead3386351fac201 to your computer and use it in GitHub Desktop.
Save PetreVane/fe3951e7e954a911ead3386351fac201 to your computer and use it in GitHub Desktop.
These 2 extensions convert a String to Date, and back to String
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())"
@soilmilk
Copy link

Yo thanks so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment