Skip to content

Commit 79bcd50

Browse files
authored
Merge pull request #8 from thejohnlima/hotfix/leap_year
Fix moon phase bug caused by leap year
2 parents 65010bd + fdb8cab commit 79bcd50

File tree

2 files changed

+10
-11
lines changed

2 files changed

+10
-11
lines changed

Sources/MoonKit/Moon.swift

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,13 @@ public class Moon {
145145
/// Calculate moon's age in days
146146
/// - Parameters:
147147
/// - dates: Dates in Julian calendar or Gregorian calendar
148-
private func getAgeInDays(_ dates: Double) -> (age: Double, ip: Double) {
148+
/// - date: The current date components
149+
private func getAgeInDays(_ dates: Double, date: ShortDate) -> (age: Double, ip: Double) {
149150
let ip = normalize((dates - 2451550.1) / 29.530588853)
150-
let age = ip * 29.53
151+
var age = ip * 29.53
152+
if isLeap(year: date.year) {
153+
age -= 1
154+
}
151155
return (age, ip)
152156
}
153157

@@ -221,17 +225,12 @@ public class Moon {
221225
let dayValue = Double(day)
222226
let julianDate = getJulianDate((yearValue, monthValue, dayValue))
223227
let dates = getCalendarDates((julianDate.year, month: julianDate.month, day: julianDate.day))
224-
let age = getAgeInDays(dates)
228+
let age = getAgeInDays(dates, date: (yearValue, monthValue, dayValue))
225229
var ip = age.ip
226230

227-
var ageValue: Double {
228-
guard isLeap(year: yearValue), monthValue == 2 else { return age.age }
229-
return age.age - 1
230-
}
231-
232-
self.age = ageValue
231+
self.age = age.age
233232

234-
preparePhase(ageValue)
233+
preparePhase(age.age)
235234

236235
// Convert phase to radians
237236
ip = ip * 2 * Double.pi

Tests/MoonKitTests/MoonKitTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ final class MoonKitTests: XCTestCase {
4444
}
4545

4646
func testMoonPhaseWaxingCrescent() {
47-
let moon = getMoon("02-26-2020 18:00")
47+
let moon = getMoon("01-31-2020 18:00")
4848
XCTAssertEqual(moon.info.phase, .waxingCrescent)
4949
}
5050

0 commit comments

Comments
 (0)