Skip to content

Instantly share code, notes, and snippets.

@jrr6
Last active January 2, 2017 22:36
Show Gist options
  • Save jrr6/45488423d63cc68a72a0 to your computer and use it in GitHub Desktop.
Save jrr6/45488423d63cc68a72a0 to your computer and use it in GitHub Desktop.
A simple Swift function to find the day of the week of a given day.
import Foundation
enum DateError: Error {
case IllegalFormat
case DayOutOfRange
}
/**
Gets the day of the week of a given date on the Gregorian calendar.
- parameter date: A date containing a month, date, and 4-digit year.
- throws: Errors of type `DateError`:
- `DateError`.`IllegalFormat` — the date string provided is not in one of the supported formats
- `DateError`.`DayOutOfRange` — the `Weekday` component of the given day is not between 1 and 7
- returns: A string containing the day of the week on which the specified date occurred.
*/
func getDay(date: String) throws -> String {
let df = DateFormatter()
df.timeStyle = .none
df.dateFormat = "MM/dd/yyyy"
var finalDate: Date!
let mmddyyyy = df.date(from: date)
if mmddyyyy == nil {
let df2 = DateFormatter()
df2.timeStyle = .none
df2.dateFormat = "MM dd, yyyy"
finalDate = df2.date(from: date)
} else {
finalDate = mmddyyyy
}
if let date = finalDate {
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let day = calendar!.component(.weekday, from: date as Date)
switch day {
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
default:
throw DateError.DayOutOfRange
}
} else {
throw DateError.IllegalFormat
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment