好久沒寫過文章,隨便擼下碼,結(jié)合Swift的特性及一些時(shí)間序列的思路。通過時(shí)間段來獲取對(duì)應(yīng)的星座。當(dāng)然還有其他更加簡(jiǎn)單的方式,大家可以搜索下。
星座時(shí)間段
肺話少說,上代碼
//
// Constellation.swift
//
// Created by 小黑Swift on 2017/7/11.
// Copyright ? 2017年 Swift. All rights reserved.
//
import Foundation
struct Constellation {
private enum ConstellationType:String {
case 白羊座, 金牛座, 雙子座, 巨蟹座, 獅子座, 處女座,
天秤座, 天蝎座, 射手座, 摩羯座, 水瓶座, 雙魚座
}
private static let constellationDict:[ConstellationType :String] = [.白羊座: "3.21-4.19",
.金牛座: "4.20-5.20",
.雙子座: "5.21-6.21",
.巨蟹座: "6.22-7.22",
.獅子座: "7.23-8.22",
.處女座: "8.23-9.22",
.天秤座: "9.23-10.23",
.天蝎座: "10.24-11.22",
.射手座: "11.23-12.21",
.摩羯座: "12.22-1.19",
.水瓶座: "1.20-2.18",
.雙魚座: "2.19-3.20"]
/// 日期 -> 星座
/// - parameter date: 日期
/// - returns: 星座名稱
public static func calculateWithDate(date: Date) -> String? {
let timeInterval = date.timeIntervalSince1970
let OneDay:Double = 86400
let currConstellation = constellationDict.filter {
let timeRange = getTimeRange(date: date, timeRange: $1)
let startTime = timeRange.0
let endTime = timeRange.1 + OneDay
return timeInterval > startTime && timeInterval < endTime
} // 摩羯座這家伙跨年必定不滿足
return currConstellation.first?.key.rawValue ?? "摩羯座"
}
/// f.獲取開始、結(jié)束時(shí)間
private static func getTimeRange(date:Date, timeRange: String) -> (TimeInterval, TimeInterval) {
/// f.1 獲取當(dāng)前年份
func getCurrYear(date:Date) -> String {
let dm = DateFormatter()
dm.dateFormat = "yyyy."
let currYear = dm.string(from: date)
return currYear
}
/// f.2 日期轉(zhuǎn)換當(dāng)前時(shí)間戳
func toTimeInterval(dateStr: String) -> TimeInterval? {
let dm = DateFormatter()
dm.dateFormat = "yyyy.MM.dd"
let date = dm.date(from: dateStr)
let interval = date?.timeIntervalSince1970
return interval
}
let timeStrArr = timeRange.components(separatedBy: "-")
let dateYear = getCurrYear(date: date)
let startTimeStr = dateYear + timeStrArr.first!
let endTimeStr = dateYear + timeStrArr.last!
let startTime = toTimeInterval(dateStr: startTimeStr)!
let endTime = toTimeInterval(dateStr: endTimeStr)!
return (startTime, endTime)
}
}
使用
let now = Date()
let constellationName = Constellation.calculateWithDate(date: now)! // 當(dāng)前時(shí)間所在星座
來個(gè)簡(jiǎn)單的Rx?? 通過日期選擇器 獲取對(duì)應(yīng) 星座
Simulator Screen Shot 2017年7月11日 下午12.21.58.png
代碼:
import UIKit
import RxCocoa
import RxSwift
class ConstellationViewController: UIViewController {
@IBOutlet weak var constellationLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!
var bag = DisposeBag()
var constellationName = Variable("??")
override func viewDidLoad() {
super.viewDidLoad()
datePicker.rx.date.subscribe(onNext: { [weak self] date in
let conName = Constellation.calculateWithDate(date: date)!
self?.constellationName.value = conName
}).addDisposableTo(bag)
constellationName.asObservable().bindTo(constellationLabel.rx.text).addDisposableTo(bag)
}
}