Skip to content

Instantly share code, notes, and snippets.

@imvenj
Last active April 11, 2018 10:21
Show Gist options
  • Save imvenj/b447a6967766553cde52ff7d23954222 to your computer and use it in GitHub Desktop.
Save imvenj/b447a6967766553cde52ff7d23954222 to your computer and use it in GitHub Desktop.
Code snippet that calculates in which year (and age), your Chinese calendar birthday will be the same day as in Gregorian calendar.
import Foundation
let cst = TimeZone(secondsFromGMT: 8 * 3600)!
func createDate(_ year: Int, _ month: Int, _ day: Int) -> Date {
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.calendar = Calendar(identifier: .gregorian)
components.timeZone = cst
return components.date!
}
func chineseDateComponents(from date: Date) -> (month: Int, day: Int, isLeap: Bool) {
let chCal = Calendar(identifier: .chinese)
let comp = chCal.dateComponents(in: cst, from: date)
return (comp.month!, comp.day!, comp.isLeapMonth!)
}
func calculateMatchForBirthDay(year: Int, month: Int, day: Int) {
let bDate = createDate(year, month, day)
let bDateCh = chineseDateComponents(from: bDate)
((year+1)...(year+100)).forEach { (aYear) in
let y = createDate(aYear, month, day)
let ych = chineseDateComponents(from: y)
if ych.month == bDateCh.month && ych.day == bDateCh.day {
let age = aYear - year
print("\(aYear), age: \(age)\(ych.isLeap ? ", leap month birthday" : "")")
}
}
}
calculateMatchForBirthDay(year: 1984, month: 12, day: 24)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment