如何将此字符串“2016-04-14T10:44:00+0000”转换为NSDate并只保留年、月、日、小时?
中间的T真的让我在处理日期时不习惯。
如何将此字符串“2016-04-14T10:44:00+0000”转换为NSDate并只保留年、月、日、小时?
中间的T真的让我在处理日期时不习惯。
当前回答
请使用ISO8601解析库来执行此操作。编码字符串的方法太多了。不要依赖于特定的格式,也不要依赖于始终发送相同的服务器。问题从末尾的“Z”开始,它将扩展到标准的所有品种。解析库将处理所有情况,并始终提供安全转换——而固定格式化字符串在将来可能会失败。
您可以使用这些库之一。CococaPods上也有:
https://github.com/boredzo/iso-8601-date-formatter/
https://github.com/malcommac/SwiftDate
看一下实现。它们都有几百行——这是有原因的。
关于这个问题:你可以使用NSDateComponents从日期中提取日期组件。网站上的例子正好符合你的情况。
https://developer.apple.com/documentation/foundation/nscalendar/1414841-components?language=objc
请注意,转换日期时会考虑到时区。你可能想显式地设置NSCalendar的locale。
其他回答
在Swift 4.1你可以做:
func getDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale.current
return dateFormatter.date(from: "2015-04-01T11:42:00") // replace Date String
}
请使用ISO8601解析库来执行此操作。编码字符串的方法太多了。不要依赖于特定的格式,也不要依赖于始终发送相同的服务器。问题从末尾的“Z”开始,它将扩展到标准的所有品种。解析库将处理所有情况,并始终提供安全转换——而固定格式化字符串在将来可能会失败。
您可以使用这些库之一。CococaPods上也有:
https://github.com/boredzo/iso-8601-date-formatter/
https://github.com/malcommac/SwiftDate
看一下实现。它们都有几百行——这是有原因的。
关于这个问题:你可以使用NSDateComponents从日期中提取日期组件。网站上的例子正好符合你的情况。
https://developer.apple.com/documentation/foundation/nscalendar/1414841-components?language=objc
请注意,转换日期时会考虑到时区。你可能想显式地设置NSCalendar的locale。
有时,在swift中将字符串转换为日期可能会导致返回nil,因此您应该在格式中添加“!”标记。日期函数!
let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"
let stringDate = "11-03-2018"
let date = dateFormatterUK.date(from: stringDate)!
我对这种格式也很着迷。
请参阅下面的解决方案。
你的字符串来自你的背部或其他来源:
let isoDate = "2020-05-06 20:00:00-03"
识别日期格式
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!
现在您已经将日期设置为date(),您可以使用formatDate.string将其更改为您想要的任何格式
let formatDate = DateFormatter()
formatDate.dateFormat = "dd/MM/yyyy HH:mm"
let drawDate = formatDate.string(from: date)
print(drawDate)
输出:
06/05/2020 20:00
从iOS 15.0开始,我们可以更快速地将字符串转换为日期:
let strategy = Date.ParseStrategy(format: "\(year: .defaultDigits)-\(month: .twoDigits)-\(day: .twoDigits)T\(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits):\(second: .twoDigits)\(timeZone: .iso8601(.short))", timeZone: .current)
let date = try? Date("2016-04-14T10:44:00+0000", strategy: strategy)