1.NSDateComponents
(1).用于计算未来或过去的时间
(2).计算时间差
2.NSDateFormatter
(1).NSDate到字符串的转换
(2).字符串到NSDate的转换
import UIKit
var str = "Hello, playground"
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
// 指定dataFormatter的dateStyle, 用NSDateFormatterStyle枚举的格式
dateFormatter.dateStyle = .FullStyle
var convertedDate = dateFormatter.stringFromDate(currentDate)
//自定义dataFormatter
dateFormatter.dateFormat = "yyyy年MM月dd日HH时mm分ss秒"
convertedDate = dateFormatter.stringFromDate(currentDate)
//字符串转NSDate
var dateString1 = "2000年01月11日13时15分12秒"
var date1 = dateFormatter.dateFromString(dateString1)
// NSDateComponents
let calendar = NSCalendar.currentCalendar()
// calendar用一个date对象转换为dateComponents
// components第二个参数是NSDate对象,第一个参数是想获得的日期的某部分
let dateComponents = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: currentDate)
dateComponents.day
dateComponents.month
dateComponents.year
// NSDateComponents转换为NSDate
let components = NSDateComponents()
components.year = 2000
components.month = 1
components.day = 11
components.hour = 11
components.minute = 23
var date2 = calendar.dateFromComponents(components)
date2
dateFormatter.dateFormat = "yyyy:MM:dd"
var dateString11 = "2011:01:03"
var dateString22 = "2011:01:10"
var date11 = dateFormatter.dateFromString(dateString11)
var date22 = dateFormatter.dateFromString(dateString22)
// earlierDate。如果date11比date22早返回date11,laterDate同理
let result1 = date11?.earlierDate(date22!)
// 用compare比较
if date11?.compare(date22!) == .OrderedAscending {
print("date11比较小")
}
// 计算日期
// 当前时间加上1个月零11天
let monthsToAdd = 1
let daysToAdd = 11
let c1 = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: monthsToAdd, toDate: currentDate, options: [])
c1
let c2 = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: daysToAdd, toDate: c1!, options: [])
c2
let newDateComponents = NSDateComponents()
newDateComponents.month = 1
newDateComponents.day = 10
let c3 = NSCalendar.currentCalendar().dateByAddingComponents(newDateComponents, toDate: currentDate, options: [])
// 计算日期的差值
// 用NSDateComponentsFormatter比较
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.unitsStyle = .Full
let interval = date22?.timeIntervalSinceDate(date11!)
dateComponentsFormatter.stringFromTimeInterval(interval!)
//
dateComponentsFormatter.allowedUnits = [.Year, .Month, .Day, .Hour, .Minute, .Second]
let result2 = dateComponentsFormatter.stringFromDate(date11!, toDate: date22!)
网友评论