Skip to content

Instantly share code, notes, and snippets.

@TiagoBras
Created April 18, 2019 11:01
Show Gist options
  • Select an option

  • Save TiagoBras/a0d19531ee58d3941e248e6702abf295 to your computer and use it in GitHub Desktop.

Select an option

Save TiagoBras/a0d19531ee58d3941e248e6702abf295 to your computer and use it in GitHub Desktop.
How I handle different Date Formats
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