在app中,展示个人信息时,有时候服务器只返回一个生日,然后要在个人信息里展示相应的星座名称和图标,这时候就需要客户端根据生日自己计算,那么怎么计算呢,方法很简单。
- 申明一个星座结构体,里面包含星座code,星座名字。
code用来标识一个星座,可以根据code来设置不同的星座图片,在需要国际化的时候根据code来展示相应的本地化字符串。
struct JPSConstellation {
///星座code
var code: Int
///星座名
var name: String
}
- 根据日期计算出星座
func constellationWith(date: Date) -> JPSConstellation? {
guard let calendar = NSCalendar(identifier: NSCalendar.Identifier.gregorian) else {
return nil
}
let components = calendar.components([.month, .day], from: date)
let month = components.month!
let day = components.day!
// 月以100倍之月作为一个数字计算出来
let mmdd = month * 100 + day;
var constellation: JPSConstellation?
if ((mmdd >= 321 && mmdd <= 331) ||
(mmdd >= 401 && mmdd <= 419)) {
constellation = JPSConstellation(code: 1, name: "白羊座")
} else if ((mmdd >= 420 && mmdd <= 430) ||
(mmdd >= 501 && mmdd <= 520)) {
constellation = JPSConstellation(code: 2, name: "金牛座")
} else if ((mmdd >= 521 && mmdd <= 531) ||
(mmdd >= 601 && mmdd <= 621)) {
constellation = JPSConstellation(code: 3, name: "双子座")
} else if ((mmdd >= 622 && mmdd <= 630) ||
(mmdd >= 701 && mmdd <= 722)) {
constellation = JPSConstellation(code: 4, name: "巨蟹座")
} else if ((mmdd >= 723 && mmdd <= 731) ||
(mmdd >= 801 && mmdd <= 822)) {
constellation = JPSConstellation(code: 5, name: "狮子座")
} else if ((mmdd >= 823 && mmdd <= 831) ||
(mmdd >= 901 && mmdd <= 922)) {
constellation = JPSConstellation(code: 6, name: "处女座")
} else if ((mmdd >= 923 && mmdd <= 930) ||
(mmdd >= 1001 && mmdd <= 1023)) {
constellation = JPSConstellation(code: 7, name: "天秤座")
} else if ((mmdd >= 1024 && mmdd <= 1031) ||
(mmdd >= 1101 && mmdd <= 1122)) {
constellation = JPSConstellation(code: 8, name: "天蝎座")
} else if ((mmdd >= 1123 && mmdd <= 1130) ||
(mmdd >= 1201 && mmdd <= 1221)) {
constellation = JPSConstellation(code: 9, name: "射手座")
} else if ((mmdd >= 1222 && mmdd <= 1231) ||
(mmdd >= 101 && mmdd <= 119)) {
constellation = JPSConstellation(code: 10, name: "摩羯座")
} else if ((mmdd >= 120 && mmdd <= 131) ||
(mmdd >= 201 && mmdd <= 218)) {
constellation = JPSConstellation(code: 11, name: "水瓶座")
} else if ((mmdd >= 219 && mmdd <= 229) ||
(mmdd >= 301 && mmdd <= 320)) {
//考虑到2月闰年有29天的
constellation = JPSConstellation(code: 12, name: "双鱼座")
}else{
print(mmdd)
print("日期错误")
constellation = nil
}
return constellation
}
- 最后可以打印验证一下
override func viewDidLoad() {
super.viewDidLoad()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
let date = formatter.date(from: "1995/1/11")
let constellation = constellationWith(date: date!)
print(constellation?.name as Any)
}
网友评论