使用 NSDate 获取复活节日期 [英] Using NSDate to get date for Easter

查看:48
本文介绍了使用 NSDate 获取复活节日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,该应用程序需要使用国定假日的日期.

I'm working on an application that requires the use of getting dates for national holidays.

在下面,我能够获得阵亡将士纪念日:

Below, I was able to get Memorial Day:

// 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 实例:

Because the dates are pretty well set, I am able to successfully create NSDate instances for the following holidays:

  • 元旦
  • 小马丁·路德·金·戴
  • 总统日
  • 纪念日
  • 独立日
  • 劳动节
  • 感恩节
  • 圣诞节

然而,我唯一不知道如何获得的就是复活节.它每年都在变化,所以我很好奇是否有其他人能够通过 API 或其他方式如此成功地获得复活节的日期.

However, the only one that I am having difficulty figuring out how to get is Easter. It varies every year, so I'm curious as to whether anyone else has been able so successfully get the date for Easter via an API or other means.

推荐答案

我找到了一个 gist 在 GitHub 上有一个准确的解决方案,用于计算和返回复活节的 NSDate.

I was able to find a gist on GitHub that has a solution that was accurate for calculating and returning an NSDate for Easter.

下面的代码是要点包含的内容:

The code below is what the gist contains:

// 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"

这篇关于使用 NSDate 获取复活节日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆