Last active
January 7, 2020 22:48
-
-
Save kevin49999/a13dc5336e5480e5759301859f123332 to your computer and use it in GitHub Desktop.
Days Between
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
| func isLeapYear(_ year: Int) -> Bool { | |
| assert(year >= 0) | |
| if year % 4 == 0 { | |
| return year % 100 != 0 || year % 400 == 0 | |
| } | |
| return false | |
| } | |
| func daysInYear(_ year: Int) -> Int { | |
| return isLeapYear(year) ? 366 : 365 | |
| } | |
| func daysInMonth(_ month: Int, year: Int) -> Int { | |
| switch month { | |
| case 1, 3, 5, 7, 8, 10, 12: | |
| return 31 | |
| case 2: | |
| return isLeapYear(year) ? 29 : 28 | |
| case 4, 6, 9, 11: | |
| return 30 | |
| default: | |
| fatalError() | |
| } | |
| } | |
| typealias Date = (month: Int, day: Int, year: Int) | |
| func daysBetween(oldDate: Date, date: Date) -> Int { | |
| let daysFromYears: Int = ((oldDate.year + 1)..<date.year) | |
| .map { return daysInYear($0) } | |
| .reduce(0, +) | |
| let daysFromOldYear: Int = (oldDate.month...12) | |
| .map { | |
| if $0 == oldDate.month { | |
| return daysInMonth($0, year: oldDate.year) - oldDate.day | |
| } | |
| return daysInMonth($0, year: oldDate.year) | |
| } | |
| .reduce(0, +) | |
| let daysFromCurrentYear: Int = (1...date.month) | |
| .map { | |
| if $0 == date.month { | |
| return date.day | |
| } | |
| return daysInMonth($0, year: date.year) | |
| } | |
| .reduce(0, +) | |
| // 🚀 | |
| let daysFromOldDate = daysFromYears + daysFromOldYear + daysFromCurrentYear | |
| return daysFromOldDate | |
| } | |
| daysBetween(oldDate: Date(month: 5, day: 22, year: 1993), date: Date(month: 9, day: 23, year: 2019)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment