Swift 的 Date、DateFormatter、DateComponents、Locale 之間的關係說明

Swift 的 Date、DateFormatter、DateComponents、Locale 之間的關係說明

前言

理解這些類之間的關係,和這些類是幹嗎的,對處理時間來講很重要node

類名 說明 注意
Date 只是表示時間的一個數據,只表示時間節點,像時間戳差很少
DateFormatter 是格式化輸出時間的
DateComponents 是盛放時間組件的,年月日時分秒等
Locale 區別於地域的日期顯示,不一樣語言的顯示, Monday星期一
Calendar 基於日曆層面的東西,好比日曆是普通日曆,仍是農曆。若是是農曆,在設置好 Locale 後,就能夠顯示 冬月 臘月

這些類的屬性和關係圖 [Minnode圖]

iOS Date 相關.png

下面是個 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
相關文章
相關標籤/搜索