我正在使用api,它给出了以下时间格式:
“071953Z”
07是当天
19是小时
53分钟
Z是祖鲁时间
正如你所看到的,目前没有月份和年份,我也想要添加,但我不知道如何。
你能帮我把它转换成现在的时间吗?谢谢!
答案 0 :(得分:0)
我认为您最好的选择是将部分日期时间存储在DateComponents
中。然后,您可以为其添加月份和年份,并使用Foundation
的日历API来执行您想要的操作:
extension DateComponents {
static func from(str: String) -> DateComponents? {
guard str.characters.count == 7 else {
return nil
}
var components = DateComponents()
components.timeZone = TimeZone(secondsFromGMT: 0)
components.calendar = Calendar(identifier: .gregorian)
let ranges = [0,2,4].map {
return str.index(str.startIndex, offsetBy: $0)..<str.index(str.startIndex, offsetBy: $0 + 2)
}
if let day = Int(str[ranges[0]]) {
components.day = day
} else {
return nil
}
if let hour = Int(str[ranges[1]]), hour < 24 {
components.hour = hour
} else {
return nil
}
if let minute = Int(str[ranges[2]]), minute < 60 {
components.minute = minute
} else {
return nil
}
return components
}
}
// This formatter is to convert the date to your local time. Configure to taste
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
if var components = DateComponents.from(str: "071953Z") {
components.year = 2017
components.month = 4
if let date = components.date {
print(formatter.string(from: date))
} else {
print("\(components) does not make a valid date")
}
}