swift之NSDate

在通常项目中一般用的最多的情况就是获取日期并格式化。
1、只需要小时、分钟、秒数时个人觉得使用以下代码

let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "HH:mm:ss"
let time = dateFormater.stringFromDate(currentDate)
2、还需要得到年月日的时候,使用以下代码(因为第一种方式获取的月份为英文)

let currentDate = NSDate()
let calendar = NSCalendar.currentCalendar()
let dateComponents = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: currentDate)
print(dateComponents.year)
print(dateComponents.month)
print(dateComponents.day)
print(dateComponents.hour)
print(dateComponents.minute)
print(dateComponents.second)
3、将字符串转化为日期

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var dateAsString = "2015-10-08 14:25:37"
let date1 = dateFormatter.dateFromString(dateAsString)
4、比较日期间隔时间(此功能经常使用)

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var dateAsString = "2015-10-08 14:25:37"
let date1 = dateFormatter.dateFromString(dateAsString)!

dateAsString = "2018-03-05 08:14:19"
let date2 = dateFormatter.dateFromString(dateAsString)!

var diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: date1, toDate: date2, options: NSCalendarOptions.init(rawValue: 0))

print("The difference between dates is: (diffDateComponents.year) years, (diffDateComponents.month) months, (diffDateComponents.day) days, (diffDateComponents.hour) hours, (diffDateComponents.minute) minutes, (diffDateComponents.second) seconds")

你可能感兴趣的:(swift之NSDate)