Skip to content

Instantly share code, notes, and snippets.

@ppth0608
Last active July 4, 2019 13:43
Show Gist options
  • Save ppth0608/40197e5b5b356727e7365d2a5d594bd3 to your computer and use it in GitHub Desktop.
Save ppth0608/40197e5b5b356727e7365d2a5d594bd3 to your computer and use it in GitHub Desktop.
String to date, Date to String
import Foundation
exntension Date {
func toString(format: String) -> String {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.dateFormat = format
return formatter.string(from: self)
}
}
extension String {
func toDate(format: String, locale: Locale? = Locale(identifier: "en_US")) -> Date? {
let dateFormatter = DateFormatter()
let calendar = Calendar(identifier: .gregorian)
dateFormatter.calendar = calendar
dateFormatter.dateFormat = format
dateFormatter.locale = locale
return dateFormatter.date(from: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment