Swift3获取系统系统间并比较

在Swift3.x 版本中一个很不错的简化,就是将获取系统时间由NSDate()修改为Date(),可千万不要认为只是改了个名称这样简单,这使得代码更加简洁。

使用Date()获取当前系统时间:

let date = Date()

分离年月日:

let calendar = Calendar.current 
var year = calendar.component(.year, from: date) 
var month = calendar.component(.month, from: date) 
var day = calendar.component(.day, from: date)

分离后,既可以使用一般的语句进行时间的比较。

以下是判定 今天是不是我生日 的代码实例(Playground):

//: Playground - noun: a place where people can play 

import UIKit 
let myBirthday = (1996, 5, 3) 
var birthYear = 0  

let date = Date() 
let calendar = Calendar.current 
var year = calendar.component(.year, from: date) 
var month = calendar.component(.month, from: date) 
var day = calendar.component(.day, from: date)
  
if month == myBirthday.1 {     
    if day == myBirthday.2 {         
        birthYear = year - 1996         
        print("It's my \(birthYear)'s birthday 👑")
     } 
}

继续阅读