我正在开发一个需要使用获取国定假日日期的应用程序。
下面,我能够得到阵亡将士纪念日:
// Set the components for Memorial Day (last Monday of May)
let memorialDayComps = NSDateComponents()
memorialDayComps.weekday = 2
memorialDayComps.month = 5
memorialDayComps.year = currentYear
var mondaysOfMay = [NSDate]()
for var i = 1; i <= 5; i++ {
memorialDayComps.weekdayOrdinal = i
let monday = calendar.dateFromComponents(memorialDayComps)
let components = calendar.components(.CalendarUnitMonth, fromDate: monday!)
if components.month == 5 {
mondaysOfMay.append(monday!)
}
}
let memorialDayDate = mondaysOfMay.last
因为日期设置得很好,我能够为以下假期成功创建 NSDate
实例:
- 元旦
- 小马丁·路德·金纪念日
- 总统日
- 阵亡将士纪念日
- 独立日
- 劳动节
- 感恩节
- 圣诞节
但是,我唯一难以弄清楚如何获得的是复活节。它每年都不同,所以我很好奇是否有其他人能够通过 API 或其他方式如此成功地获得复活节的日期。
最佳答案
我找到了 gist在 GitHub 上有一个解决方案可以准确计算和返回复活节的 NSDate
。
下面的代码是要点包含的内容:
// Easter calculation in swift after Anonymous Gregorian algorithm
// Also known as Meeus/Jones/Butcher algorithm
func easter(Y : Int) -> NSDate {
let a = 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 i = 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"
关于swift - 使用 NSDate 获取复活节日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30836183/