本文将演示如何计算两个日期之间的差值。
在项目导航区,打开视图控制器的代码文件【ViewController.swift】
1 import UIKit 2 3 class ViewController: UIViewController { 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 // Do any additional setup after loading the view, typically from a nib. 8 9 //创建第一个日期对象,其值为当前设备的时间 10 let dateA = Date() 11 //创建第二个日期对象,自定义它的时间 12 let dateB = Date(timeInterval: -60*60*24*1000, since: Date()) 13 14 //判断设备的版本号是否在8以上,以执行后面的代码 15 if #available(iOS 8.0, *) 16 { 17 //初始化一个日历对象, 18 //日历对象通常用于处理与时间相关的问题。 19 //比如比较时间的前后,计算日期间差别等。 20 //日历对象支持多种历法,这里采用阳历。 21 let calendar = NSCalendar(identifier: NSCalendar.Identifier.gregorian) 22 //根据两个时间点,定义一个日期组件对象, 23 //从而快速获得这两个时间点的差值 24 let components = calendar?.components([NSCalendar.Unit.year,NSCalendar.Unit.month,NSCalendar.Unit.day], from: dateA, to: dateB, options: NSCalendar.Options.matchFirst) 25 26 //在控制台打印输出两个日期相差的天数 27 print("Day:(String(describing: components?.day))") 28 //在控制台打印输出两个日期相差的月数 29 print("Month:(String(describing: components?.month))") 30 //在控制台打印输出两个日期相差的年数 31 print("Year:(String(describing: components?.year))") 32 } 33 } 34 35 override func didReceiveMemoryWarning() { 36 super.didReceiveMemoryWarning() 37 // Dispose of any resources that can be recreated. 38 } 39 }