Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active September 11, 2019 02:06
Show Gist options
  • Save pauljohanneskraft/d42e7d5e2b620f160d8d79313af95c10 to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/d42e7d5e2b620f160d8d79313af95c10 to your computer and use it in GitHub Desktop.
returns the day of the week of any date between 01.01.1700 to 31.12.2199

DayOfTheWeek

This function returns the weekday of any date between 1700 and 2199.

print(try dayOfTheWeek("28.09.1964")) // Prints "Monday"
print(try dayOfTheWeek("12.03.2014")) // Prints "Wednesday"
print(try dayOfTheWeek("31.12.1980")) // Prints "Wednesday"
/// please insert date in DD.MM.YYYY pattern
func dayOfTheWeek(_ string: String) throws -> String {
guard string.characters.count == 10 else { throw DayOfTheWeekError.wrongFormat("length") }
var index0 = string.startIndex
var index1 = string.index(index0, offsetBy: 2)
guard let dayCode = UInt16(string[index0..<index1]) else { throw DayOfTheWeekError.wrongFormat("day") }
index0 = string.index(index1, offsetBy: 1)
index1 = string.index(index0, offsetBy: 2)
guard let monthCode = UInt16(string[index0..<index1]) else { throw DayOfTheWeekError.wrongFormat("month") }
index0 = string.index(index1, offsetBy: 1)
index1 = string.index(index0, offsetBy: 4)
guard let yearCode = UInt16(string[index0..<index1]) else { throw DayOfTheWeekError.wrongFormat("year") }
let leapYear = yearCode % 4 == 0 ? (yearCode % 100 == 0 ? (yearCode % 400 != 0) : true) : false
var result : UInt16 = dayCode
switch monthCode {
case 1 : result += leapYear ? 5 : 6
case 2 : result += leapYear ? 1 : 2
case 3 : result += 2
case 4 : result += 5
case 5 : result += 0
case 6 : result += 3
case 7 : result += 5
case 8 : result += 1
case 9 : result += 4
case 10 : result += 6
case 11 : result += 2
case 12 : result += 4
default : throw DayOfTheWeekError.wrongFormat("month")
}
let y = yearCode % 100
result += (y / 4) + y
switch yearCode / 100 {
case 17 : result += 5
case 18 : result += 3
case 19 : result += 1
case 20 : result += 0
case 21 : result += 5
default : throw DayOfTheWeekError.wrongFormat("year")
}
switch result % 7 {
case 1 : return "Monday"
case 2 : return "Tuesday"
case 3 : return "Wednesday"
case 4 : return "Thursday"
case 5 : return "Friday"
case 6 : return "Saturday"
case 0 : return "Sunday"
default : fatalError("\(result % 7) < 0 ?... because it's not in 0..<7.")
}
}
enum DayOfTheWeekError : Error {
case wrongFormat(String)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment