The swift NSDate

Generally the most used in the normal situation is to get the date and format project.
1, only hours, minutes, the seconds personally feel that using the following code

dateFormater = NSDateFormatter the let ()
dateFormater.dateFormat = "HH: mm: SS"
the let Time = dateFormater.stringFromDate (currentDate)
2, also need to be the date when using the following codes (because the first month is a way to get English)

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、将字符串转化为日期

dateFormatter = NSDateFormatter the let ()
dateFormatter.dateFormat = "the MM-dd-YYYY HH: mm: SS"
var dateAsString = "2015-10-08 14:25:37"
the let date1 = dateFormatter.dateFromString (dateAsString)
. 4, Comparative Date interval (this feature is often used)

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")

Guess you like

Origin www.cnblogs.com/flutter-cn/p/11222715.html