1.ViewController.swift
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //取得日期 let date = NSDate() println(date) //原始 var formatter = NSDateFormatter(); formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"; let date2 = formatter.stringFromDate(date); println(date2) //格式為yyyy-MM-dd HH:mm:ss formatter.dateFormat = "yyyy/MM/dd"; let date3 = formatter.stringFromDate(date); println(date3)//格式為yyyy/MM/dd //比較時間 //現在時間 let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Month, .Day], fromDate: date) //只取月,日 let dateNow = String(format: "%02d-%02d", components.month, components.day) //NSDate 轉 字串(格式 日-月) //自設時間 let formatter = NSDateFormatter() formatter.dateFormat = "MM-dd" //日期格式 formatter.timeZone = NSTimeZone(name: "UTC") let dateSet = "03-29" //自設時間 let dateA = formatter.dateFromString(dateNow)! //字串 轉 NSDate let dateB = formatter.dateFromString(dateSet)! //字串 轉 NSDate print("DateA:\(dateA)") print("DateB:\(dateB)") // 比較 switch dateA.compare(dateB) { case .OrderedAscending : print("Date A 比 date B 早") case .OrderedDescending : print("Date A 比 date B 晚") case .OrderedSame : print("同日") } } }參考來源:
http://www.brianjcoleman.com/tutorial-nsdate-in-swift/
http://iswift.org/cookbook/compare-2-dates
沒有留言 :
張貼留言