Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Created August 13, 2023 17:25
Show Gist options
  • Save andresr-dev/1cfd448de72ada71d177518f3b18631a to your computer and use it in GitHub Desktop.
Save andresr-dev/1cfd448de72ada71d177518f3b18631a to your computer and use it in GitHub Desktop.
This is a handy way to give format to your dates in swift
enum DateFormatSelector: String {
/// AM or PM only
case a = "a"
case MMMM = "MMMM"
case yyyy = "yyyy"
case Hmm = "H:mm"
/// The 24-hour hour padding with a zero if there is only 1 digit.
case HHmm = "HH:mm"
/// The 12-hour hour padding with a zero if there is only 1 digit
case hhmm = "hh:mm"
case hmma = "h:mm a"
case MMddyyyy = "MM/dd/yyyy"
case yyyyMMdd = "yyyy-MM-dd"
case MMMddyyyy = "MMM dd, yyyy"
case MMddyyyyHHmm = "MM/dd/YYYY HH:mm"
case yyyyMMddhmma = "yyyy-MM-dd h:mm a"
case EMMMdyyyy = "E, MMM d yyyy"
case EEEEMMMMddyyyy = " EEEE, MMMM dd, yyyy'"
case yyyyMMddTHHmmssSSSZ = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
}
extension String {
/// Convert a String to Date
/// - Parameter format: Format of the string date to be converted
/// - Returns: Date type with the date of the string
func toDate(format: DateFormatSelector) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format.rawValue
return dateFormatter.date(from: self) ?? .now
}
/// Convert a String in a certain date format to another
/// string in another format
/// - Parameters:
/// - fromFormat: Date format origin
/// - toFormat: Date format destination
/// - Returns: String with the desired format
func toDateString(fromFormat: DateFormatSelector, toFormat: DateFormatSelector) -> String {
let date: Date = self.toDate(format: fromFormat)
return date.toString(format: toFormat)
}
}
extension Date {
/// Convert a Date to a string in a desired format
/// - Parameter format: Format destination
/// - Returns: String with the date in the desired format
func toString(format: DateFormatSelector) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format.rawValue
return dateFormatter.string(from: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment