Last active
May 6, 2020 16:06
-
-
Save jimbrayrcp/ee69edaab53dea7b1aa7cdd13ede7d6b to your computer and use it in GitHub Desktop.
Swift 5: iOS: 13.1 Date formatter and converter: Converts: dateString to Date dateString to Formatted Date String date to Formatted date string
This file contains 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
import Foundation | |
// USE: | |
var dateString = "14.05.2020T10:30:10" | |
let dateFormat = DateFormatter(format: "dd.MM.yyyy'T'HH:mm:ss") | |
let dateFormat1 = DateFormatter(format: "MM/dd/yyyy '@' HH:mm") | |
let date = Date() | |
print("date String -> toDate: \(dateString.toDate(dateFormatter: dateFormat)!)") | |
print("date String -> toDateString: \(dateString.toDateString(dateFormatter: dateFormat, outputFormat: "MM/dd/yy")!)") | |
print("Date -> formated string: \(date.toString(dateFormatter: dateFormat1)!)") | |
extension DateFormatter { | |
convenience init(format: String) { | |
self.init() | |
dateFormat = format | |
locale = Locale.current | |
} | |
} | |
extension String { | |
func toDate(dateFormatter: DateFormatter) -> Date? { | |
return dateFormatter.date(from: self) | |
} | |
func toDateString(dateFormatter: DateFormatter, outputFormat: String) -> String? { | |
guard let date = toDate(dateFormatter: dateFormatter) else { return nil } | |
return DateFormatter(format: outputFormat).string(from: date) | |
} | |
} | |
extension Date { | |
func toString(dateFormatter: DateFormatter) -> String? { | |
return dateFormatter.string(from: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment