理解这些类之间的关系,和这些类是干吗的,对处理时间来讲很重要node
类名 | 说明 | 注意 |
---|---|---|
Date | 只是表示时间的一个数据,只表示时间节点,像时间戳差很少 | |
DateFormatter | 是格式化输出时间的 | |
DateComponents | 是盛放时间组件的,年月日时分秒等 | |
Locale | 区别于地域的日期显示,不一样语言的显示, Monday 对 星期一 |
|
Calendar | 基于日历层面的东西,好比日历是普通日历,仍是农历。若是是农历,在设置好 Locale 后,就能够显示 冬月 腊月 |
下面是个 PlayGround
文件,能够复制到 PlayGround
中测试swift
import Foundation // MARK: Date let dateNow = Date() // MARK: Calendar var calendar = Calendar(identifier: .gregorian) var calendarChinese = Calendar(identifier: .chinese) /// 若是是 .chinese,下面获取到的 components 就是农历的,好比:若是 .day=22 就是‘廿二’的意思 /// 月份也是同样,像下面的 冬月 腊月 calendar.locale = Locale(identifier: "zh_CN") calendar.weekdaySymbols /// ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] calendar.monthSymbols /// ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"] calendarChinese.locale = Locale(identifier: "zh_CN") calendarChinese.weekdaySymbols /// ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] calendarChinese.monthSymbols /// ["正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月"] var nowDateComponents = calendar.dateComponents([.year, .month, .day], from: dateNow) nowDateComponents.day = nowDateComponents.day! + 1 let date1HourBefore = dateNow - 60*60 let dateComponents = calendar.date(from: nowDateComponents)! // MARK: DateFormatter let dateFormatter = DateFormatter() dateFormatter.timeStyle = .short dateFormatter.dateStyle = .medium dateFormatter.locale = Locale.current dateFormatter.dateFormat = "Y-MM-dd HH:mm:ss" dateFormatter.calendar = calendarChinese dateFormatter.weekdaySymbols /// ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dateFormatter.monthSymbols /// ["First Month", "Second Month", "Third Month", "Fourth Month", "Fifth Month", "Sixth Month", "Seventh Month", "Eighth Month", "Ninth Month", "Tenth Month", "Eleventh Month", "Twelfth Month"] dateFormatter.locale = Locale(identifier: "zh_CN") dateFormatter.calendar = calendar dateFormatter.weekdaySymbols /// ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dateFormatter.monthSymbols /// ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] dateFormatter.string(from: dateNow) // 2020-02-15 10:15:01 dateFormatter.string(from: date1HourBefore) // 2020-02-15 09:15:01 dateFormatter.string(from: dateComponents) // 2020-02-16 00:00:00