更新时间:2022-04-20 05:20:18
将 ISO8601 字符串转换为日期
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!
从日期中获取年、月、日和小时的日期组件
Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
最后创建一个新的Date
对象并去掉分秒
let finalDate = calendar.date(from:components)
还要考虑 iOS 10/macOS 12 中引入的便利格式化程序 ISO8601DateFormatter
:
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!