Created
April 18, 2019 11:01
-
-
Save TiagoBras/a0d19531ee58d3941e248e6702abf295 to your computer and use it in GitHub Desktop.
How I handle different Date Formats
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
| import Foundation | |
| enum DateFormat: String { | |
| /// Format: yyyy-MM-dd | |
| case yyyyMMdd = "yyyy-MM-dd" | |
| /// Format: yyyy-MM-DD HH:mm | |
| case yyyyMMddHHmm = "yyyy-MM-DD HH:mm" | |
| /// Format: dd/MM/yyyy HH:mm:ss | |
| case ddMMyyyyHHmmss = "dd/MM/yyyy HH:mm:ss" | |
| /// Format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z' | |
| case iso8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" | |
| } | |
| extension Date { | |
| func format(with dateFormat: DateFormat) -> String { | |
| let dateFormatter = DateFormatter() | |
| dateFormatter.dateFormat = dateFormat.rawValue | |
| return dateFormatter.string(from: self) | |
| } | |
| init?(from text: String, dateFormat: DateFormat) { | |
| let dateFormatter = DateFormatter() | |
| dateFormatter.dateFormat = dateFormat.rawValue | |
| if let date = dateFormatter.date(from: text) { | |
| self = date | |
| } else { | |
| return nil | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment