DateFormatter

最近遇到一個問題。一個關於時間的 UI 顯示,須要顯示上午/下午。通常來講,就是在 DateFormatter 裏面進行設置 dateFormat 便可。可是通常都是AM/PM。後來發現 iOS/macOS 比較均可以顯示上午/下午的。蘋果的開發團隊不可能還傻到得本身去算時間吧。因而看 DateFormmatter 的文檔,發現了 Locale 這個東西。html

說了這麼多廢話。總算進主題了。該篇是整理下 DateFormatter。老司機就不用往下看了。?。swift

DateFormatter 使用

DateFormatter 的使用比較簡單。通常的話,很常見的用法就是用 DateFormatter 將 Date 和 String 互換。看?。app

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY年MM月dd日 HH:mm:ss"
dateFormatter.string(from: date)

dateFormat的格式,實際上是遵照Unicode Technical Standardide

To specify a custom fixed format for a date formatter, you use setDateFormat:. The format string uses the format patterns from the Unicode Technical Standard #35. The version of the standard varies with release of the operating system:

OS X v10.9 and iOS 7 use version tr35-31.ui

OS X v10.8 and iOS 6 use version tr35-25.code

不一樣系統版本遵循的格式範圍不一樣。不過如今廣泛都是 iOS 7 以上適配了。orm

在 Unicode Technical Standard 中,Date Format Patterns支持的格式挺多的。這裏只列一些經常使用的。htm

Field symbol Description
年份 y 正常的年份顯示,能夠用多種組合。
U 表示農曆年份,干支紀法。好比 甲子、丁酉。可是須要配合CalendarLocale使用
月份 M 表示 monthSymbols。 M/MM表示月份的數字,如 1/01;MMM表示簡寫月份,對應着shortMonthSymbols,如 Jun;MMMM表示標準月份,對應着monthSymbols,如 June;MMMMM表示最簡的月份表示,對應着veryShortMonthSymbols,如一月份是 J
L 表示 standaloneMonthSymbols。類同 M 的表示方法。
天數 d 表示一個月中的第幾天,d/dd表示 1/01 的區別
D 表示一年中的第幾天,可D/DD/DDD
w 表示一年中的第幾周,可w/ww
W 表示一個月中的第幾周,可W
E 表示周幾這樣。好比星期日。E\EE\EEE->Sun, EEEE->Sunday, EEEEE->S。還能夠搭配 Calendar 和 Locale,顯示中文的 週日/星期日/日
c 同 E。可是主要是是對應standaloneWeekday。搭配組合規則同 E
時鐘 h 12小時制。可h/hh
H 24小時制。可H/HH
分鐘 m 分數。可m/mm
秒鐘 s 秒數。可s/ss

經常使用的一些組合,大概是以上這些。按照Unicode Date Format的話,其實還有季度、毫秒級的一些表示。ip

好比今日是 2018年1月16日。那麼經過 DateFormatter 表示農曆日期,能夠是ci

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY年MM月dd日 HH:mm:ss"
dateFormatter.string(from: date)
dateFormatter.locale = Locale(identifier: "zh_CN")
dateFormatter.calendar = Calendar(identifier: .chinese)
dateFormatter.dateStyle = .medium
dateFormatter.dateFormat = "U年MMMd EEE a" 
dateFormatter.string(from: date) // 丁酉年冬月三十 週二 下午

其中,能夠針對 DateFormatter 的 monthSymbols 等一些屬性,設置咱們特有的一些表示習慣。好比,一月咱們但願顯示是正月,而冬月和臘月則顯示十一月、十二月。那麼能夠經過這樣進行設置。

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY年MM月dd日 HH:mm:ss"
dateFormatter.string(from: date)
dateFormatter.locale = Locale(identifier: "zh_CN")
dateFormatter.calendar = Calendar(identifier: .chinese)
dateFormatter.dateStyle = .medium
dateFormatter.shortMonthSymbols = ["正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
dateFormatter.dateFormat = "U年MMMd EEE a"
dateFormatter.string(from: date) // 丁酉年十一月三十 週二 下午

大概就這些了吧。

參考

Date and Time Programming Guide

Unicode Technical Standard

Date Format Patterns

相關文章
相關標籤/搜索