Using NSDate to get date for Easter -
i'm working on application requires use of getting dates national holidays.
below, able memorial day:
// set components memorial day (last monday of may) let memorialdaycomps = nsdatecomponents() memorialdaycomps.weekday = 2 memorialdaycomps.month = 5 memorialdaycomps.year = currentyear var mondaysofmay = [nsdate]() var = 1; <= 5; i++ { memorialdaycomps.weekdayordinal = let monday = calendar.datefromcomponents(memorialdaycomps) let components = calendar.components(.calendarunitmonth, fromdate: monday!) if components.month == 5 { mondaysofmay.append(monday!) } } let memorialdaydate = mondaysofmay.last
because dates pretty set, able create nsdate
instances following holidays:
- new year's day
- martin luther king, jr. day
- presidents' day
- memorial day
- independence day
- labor day
- thanksgiving day
- christmas day
however, 1 having difficulty figuring out how easter. varies every year, i'm curious whether else has been able date easter via api or other means.
i able find gist on github has solution accurate calculating , returning nsdate
easter.
the code below gist contains:
// easter calculation in swift after anonymous gregorian algorithm // known meeus/jones/butcher algorithm func easter(y : int) -> nsdate { let = y % 19 let b = int(floor(double(y) / 100)) let c = y % 100 let d = int(floor(double(b) / 4)) let e = b % 4 let f = int(floor(double(b+8) / 25)) let g = int(floor(double(b-f+1) / 3)) let h = (19*a + b - d - g + 15) % 30 let = int(floor(double(c) / 4)) let k = c % 4 let l = (32 + 2*e + 2*i - h - k) % 7 let m = int(floor(double(a + 11*h + 22*l) / 451)) let components = nsdatecomponents() components.year = y components.month = int(floor(double(h + l - 7*m + 114) / 31)) components.day = ((h + l - 7*m + 114) % 31) + 1 components.timezone = nstimezone(forsecondsfromgmt: 0) let cal = nscalendar(calendaridentifier: nsgregoriancalendar) return cal.datefromcomponents(components) } println(easter(2014)) // "2014-04-20 00:00:00 +0000"
Comments
Post a Comment