/**
通过日期获取星座
- 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)]
}
}