Swift 3.0---通过日期获取星座
2016-10-20 本文已影响325人
太二道士
主要思路是使用NSCalendar获取到当前的月份和日,然后月以100倍之月作为一个数字计算出来进行对比时间,获取到星座,代码如下,使用Swift 3.0编译通过
import UIKit
class Constellation: NSObject {
/**
通过日期获取星座
- parameter date: 日期
- returns: 星座名称
*/
class func calculateWithDate(date: Date) -> String {
guard let calendar = NSCalendar(identifier: NSCalendar.Identifier.gregorian) else {
return ""
}
let components = calendar.components([.month, .day], from: date)
let month = components.month!
let day = components.day!
// 月以100倍之月作为一个数字计算出来
let mmdd = month * 100 + day;
var result = ""
if ((mmdd >= 321 && mmdd <= 331) ||
(mmdd >= 401 && mmdd <= 419)) {
result = "白羊座"
} else if ((mmdd >= 420 && mmdd <= 430) ||
(mmdd >= 501 && mmdd <= 520)) {
result = "金牛座"
} else if ((mmdd >= 521 && mmdd <= 531) ||
(mmdd >= 601 && mmdd <= 621)) {
result = "双子座"
} else if ((mmdd >= 622 && mmdd <= 630) ||
(mmdd >= 701 && mmdd <= 722)) {
result = "巨蟹座"
} else if ((mmdd >= 723 && mmdd <= 731) ||
(mmdd >= 801 && mmdd <= 822)) {
result = "狮子座"
} else if ((mmdd >= 823 && mmdd <= 831) ||
(mmdd >= 901 && mmdd <= 922)) {
result = "处女座"
} else if ((mmdd >= 923 && mmdd <= 930) ||
(mmdd >= 1001 && mmdd <= 1023)) {
result = "天秤座"
} else if ((mmdd >= 1024 && mmdd <= 1031) ||
(mmdd >= 1101 && mmdd <= 1122)) {
result = "天蝎座"
} else if ((mmdd >= 1123 && mmdd <= 1130) ||
(mmdd >= 1201 && mmdd <= 1221)) {
result = "射手座"
} else if ((mmdd >= 1222 && mmdd <= 1231) ||
(mmdd >= 101 && mmdd <= 119)) {
result = "摩羯座"
} else if ((mmdd >= 120 && mmdd <= 131) ||
(mmdd >= 201 && mmdd <= 218)) {
result = "水瓶座"
} else if ((mmdd >= 219 && mmdd <= 229) ||
(mmdd >= 301 && mmdd <= 320)) {
//考虑到2月闰年有29天的
result = "双鱼座"
}else{
print(mmdd)
result = "日期错误"
}
return result
}
}
使用方法
let constellation = Constellation.calculateWithDate(date: Date())
print(constellation)