Created
November 14, 2018 15:35
-
-
Save stinger/d6e20d20210d655b8bc32fd5b2d00bd8 to your computer and use it in GitHub Desktop.
Functional date formatting
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 | |
extension Date { | |
typealias FormattedString = (DateFormatter) -> String | |
func formatted(by format: String) -> FormattedString { | |
return { formatter in | |
formatter.dateFormat = format | |
return formatter.string(from: self) | |
} | |
} | |
} | |
extension String { | |
typealias ParsedDate = (DateFormatter) -> Date? | |
func parse(as format: String) -> ParsedDate { | |
return { formatter in | |
formatter.dateFormat = format | |
return formatter.date(from: self) | |
} | |
} | |
} | |
let date = Date() | |
let formatter = DateFormatter() | |
formatter.locale = Locale(identifier: "bg_BG") | |
formatter.timeZone = TimeZone(abbreviation: "EEST") | |
let localised = date.formatted(by: "d MMMM, YYYY")(formatter) | |
print("Formatted with locale: \(localised)") | |
let formatted = date.formatted(by: "yyyy-MM-dd'T'HH:mm:ssZZZZZ")(formatter) | |
print("Formatted using RFC3339: \(formatted)") | |
if let outputDate = formatted.parse(as: "yyyy-MM-dd'T'HH:mm:ssZZZZZ")(formatter) { | |
print("Parsed from RFC3339 formatted string: \(outputDate)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment