如何将此字符串“2016-04-14T10:44:00+0000”转换为NSDate并只保留年、月、日、小时?
中间的T真的让我在处理日期时不习惯。
如何将此字符串“2016-04-14T10:44:00+0000”转换为NSDate并只保留年、月、日、小时?
中间的T真的让我在处理日期时不习惯。
当前回答
创建全局函数
func convertDateFormat(inputDate: String) -> String {
let olDateFormatter = DateFormatter()
olDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let oldDate = olDateFormatter.date(from: inputDate)
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "MMM dd yyyy h:mm a"
return convertDateFormatter.string(from: oldDate!)
}
调用函数并在其中传递值
get_OutputStr = convertDateFormat(inputDate: "2019-03-30T05:30:00+0000")
这里是输出
Feb 25 2020 4:51 PM
其他回答
请使用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。
那SwiftDate呢?Swift最好的日期和时间解析和操作库。
https://github.com/malcommac/SwiftDate#1-date-parsing
使用可可豆荚安装: https://github.com/malcommac/SwiftDate/blob/master/Documentation/0.Informations.md#installation
然后:
import SwiftDate
// All default datetime formats (15+) are recognized automatically
let _ = "2010-05-20 15:30:00".toDate()
// You can also provide your own format!
let _ = "2010-05-20 15:30".toDate("yyyy-MM-dd HH:mm")
// All ISO8601 variants are supported too with timezone parsing!
let _ = "2017-09-17T11:59:29+02:00".toISODate()
// RSS, Extended, HTTP, SQL, .NET and all the major variants are supported!
let _ = "19 Nov 2015 22:20:40 +0100".toRSS(alt: true)
在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
}
就用SwifterSwift吧。
stringDate = "2020-04-26T08:56:17.987Z"
let date = Date(iso8601String: stringDate)
斯威夫特5。看是否一个日期已经通过:
let expiryDate = "2020-01-10" // Jan 10 2020
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if Date() < dateFormatter.date(from: expiryDate) ?? Date() {
print("Not Yet expiryDate")
} else {
print("expiryDate has passed")
}