格式参考地址 http://blog.csdn.net/imanapple/article/details/43447825
格式化时间 Date -> String
你可能会查到要用NSDate里面的方法来实现,但打开
NSdate
API的时候会发现里面的方法基本都已经废弃了,会告诉你应该用Date
里面的方法,本文主要用到 三个类Date
,DateFormatter
,DateComponentsFormatter
let currentDate = Date() // 获取当前时间
let dateFormatter = DateFormatter()
// DateFormatter 看名字就知道是格式化时间的类
dateFormatter.locale = Locale(identifier: "zh_CN")
// 设置时间地域,不然输出的是格林尼制时间
dateFormatter.setLocalizedDateFormatFromTemplate("yyyyMMdd HHmmss")
// 定义输出的内容格式 yyyy 年, MM 月, dd 日, HH 24小时,mm 分, ss 秒
dateFormatter.string(from: currentDate)
// 创建currentDate 的时间 String
// 输出 2017/06/15 22:14:17
时间字符串 转换成 时间 String -> Date
比如你用一个这样的时间String
let pastDateString = "2017-06-14 12:12:23"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "zh_CN")
dateFormatter.setLocalizedDateFormatFromTemplate("yyyyMMdd HHmmss")
// 这个时间格式需要跟你要转换的时间 String 匹配,不然转换返回的是 nil
let pastDate = dateFormatter.date(from: pastDateString)
// 返回该时间字符串转换而成的时间
计算两个时间之间的差
// 计算 pastDate 和 CurrentDate 两个时间的差
let dateComponentFormatter = DateComponentsFormatter()
// 计算差要用到这个类
dateComponentFormatter.string(from: pastDate!, to: currentDate)
// 计算 从 pastDate 到 CurrentDate 之间的差
// 输出 "1d 10:01:54"