[Swift] 如何取得現在的西元日期?

在 Swift 中,我們很常以手機的日期送資料到網頁或是 Server,但因為我們有時區的差異,以台灣或是北京/香港的時區來說,可能就要 +8 小時,而如果是日本來說,可能就要 +9 小時。而我們如何取得手機的日期呢?其實很簡單的唷。

swift 1

海芋是習慣將取日期的寫成擴充,因為這個函式實在太常用到了,而因為有些國家有比較特殊的曆制,如泰國是採用佛曆,日本也有特殊的曆法。因此,如果我們要取西元年,必須先設定好日期為 ISO8601 ,而時區 Asia/Taipei 代表台北時間,Asia/Shanghai 代表上海時間,Asia/Tokyo 代表東京時間,可以從「 Stakeoverflow」這篇文章知道所有的時區應該如何設定。

extension Date {
    //日期 -> 字符
    func date2String(dateFormat:String) -> String {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.timeZone = TimeZone(identifier:"Asia/Taipei")
        formatter.locale = Locale.init(identifier: "zh_Hant_TW")
        formatter.dateFormat = dateFormat
        let date = formatter.string(from: self)
        return date
    }
}    

而要使用的方式也很簡單,只要用這列的方式,就能取出時間囉


let date = Date().date2String(dateFormat: "yyyy/MM/dd")
print(date)
// print: 2022/02/16

而關於 Dateformat 也可以印出時、分、秒唷,如果要更多的設定,可以參考這篇文章


let date = Date().date2String(dateFormat: "yyyy/MM/dd HH:mm:ss")
print(date)
// print: 2022/02/16 04:30:14
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments