Swift 的 Date、DateFormatter、DateComponents、Locale 之间的关系说明

前言

理解这些类之间的关系,和这些类是干嘛的,对处理时间来说很重要

类名 说明 注意
Date 只是表示时间的一个数据,只表示时间节点,像时间戳差不多
DateFormatter 是格式化输出时间的
DateComponents 是盛放时间组件的,年月日时分秒等
Locale 区别于地域的日期显示,不同语言的显示, Monday星期一
Calendar 基于日历层面的东西,比如日历是普通日历,还是农历。如果是农历,在设置好 Locale 后,就可以显示 冬月 腊月

这些类的属性和关系图 [Minnode图]

iOS Date 相关.png

下面是个 PlayGround 文件,可以复制到 PlayGround 中测试

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

KyleBing
659 声望18 粉丝

前端,喜欢 Javascript scss,喜欢做一些实用的小工具