如何将该字符串"2016-04-14T10:44:00+0000"转换为,NSDate并仅保留年,月,日,小时?
"2016-04-14T10:44:00+0000"
NSDate
它T的中间部分真的使我不习惯使用日期时。
T
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)!
从日期获取年,月,日和小时的日期部分
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
最后创建一个新Date对象并删除分钟和几秒钟
Date
let finalDate = calendar.date(from:components)
还请考虑ISO8601DateFormatteriOS 10 / macOS 12中引入的便捷格式化程序:
ISO8601DateFormatter
let isoDate = "2016-04-14T10:44:00+0000" let dateFormatter = ISO8601DateFormatter() let date = dateFormatter.date(from:isoDate)!