swift---通过日期获取星座

/**
 通过日期获取星座
 
 - parameter date: 日期
 
 - returns: 星座名称
 */
class func calculateConstellationWithDate(date: NSDate) -> String {
    guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
        return ""
    }
    let components = calendar.components([.Month, .Day], fromDate: date)
    let month = components.month
    let day = components.day
    let astroString = "魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯"
    let astroFormat = "102123444543"
    
    guard (month < 1 || month > 12 || day < 1 || day > 31) == false else {
        return "错误日期格式"
    }
    guard (month == 2 && day > 29) == false else {
        return "错误日期格式"
    }
    guard ((month==4 || month==6 || month==9 || month==11) && day > 30) == false else {
        return "错误日期格式"
    }
    guard let astro: Int = Int(astroFormat[month - 1...month]) else {
        return "错误日期格式"
    }
    let isMore = day < (astro - (-19))
    
    let start = isMore ? (month * 2 - 1 * 2) : (month * 2 - 0 * 2)
    let result = astroString[start...(start + 1)] + "座"
    return result
}

这里需要用到一个String的extension

/**
 截取字符串
 
 - parameter r: 范围
 
 - returns: 返回结果
 */
subscript (r: Range<Int>) -> String {
    get {
        let startIndex = self.startIndex.advancedBy(r.startIndex)
        let endIndex = self.startIndex.advancedBy(r.endIndex)
        return self[Range(startIndex..<endIndex)]
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • title: "Swift 中枚举高级用法及实践"date: 2015-11-20tags: [APPVENTUR...
    guoshengboy阅读 2,626评论 0 2
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,785评论 18 399
  • 132.转换错误成可选值 通过转换错误成一个可选值,你可以使用 try? 来处理错误。当执行try?表达式时,如果...
    无沣阅读 1,293评论 0 3
  • 1、随机数 不需要随机数种子 arc4random()%N + begin:产生begin~begin+N的随机数...
    我是小胡胡123阅读 4,259评论 0 2