我从API获取一个字符串,其中包含日期和时间为:
createdAt = "2019-08-12T10:34:05.000Z"
我还需要从该字符串和时间中提取日期。 又如何获得两个给定日期字符串之间的时间差?
例如如果我有两个字符串:
StartedOn = "2019-08-12T10:32:18.000Z"
StopedOn = "2019-08-12T10:34:05.000Z".
如何获得从开始到停止的时间。
swift 4,Xcode 10
答案 0 :(得分:0)
尝试使用:D
import datetime
StartedOn = "2019-08-12T10:32:18.000Z"
StopedOn = "2019-08-12T10:34:05.000Z"
StartedOn = datetime.datetime.fromisoformat(StartedOn[:-1])
StoppedOn = datetime.datetime.fromisoformat(StopedOn[:-1])
print(StoppedOn - StartedOn)
答案 1 :(得分:0)
使用 DateFormatter
从Date
中获取String
实例,即
let str = "2019-08-12T10:34:05.000Z"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = formatter.date(from: str)
现在,要获取时差,请将timeIntervalSince(_:)
与2个Date
对象一起使用,即
let startedOn = "2019-08-12T10:32:18.000Z"
let stoppedOn = "2019-08-12T10:34:05.000Z"
if let startedOnDate = formatter.date(from: startedOn), let stoppedOnDate = formatter.date(from: stoppedOn) {
let timeInterval = stoppedOnDate.timeIntervalSince(startedOnDate)
print(timeInterval)
}
如果您需要2个Date
对象之间更详细的组件,请像这样使用Calendar
对象,
if let startedOnDate = formatter.date(from: startedOn), let stoppedOnDate = formatter.date(from: stoppedOn) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.hour, .minute, .second], from: startedOnDate, to: stoppedOnDate)
print(components) //hour: 0 minute: 1 second: 47
}
编辑:
要将date
和time
与Date
对象分开,
let str = "2019-08-12T10:34:05.000Z"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = formatter.date(from: str) {
formatter.dateFormat = "hh:mm:ss a"
let timeStr = formatter.string(from: date)
print(timeStr) //add timeStr to your timeLabel here...
formatter.dateFormat = "yyyy-MM-dd"
let dateStr = formatter.string(from: date)
print(dateStr) //add dateStr to your dateLabel here...
}
答案 2 :(得分:0)
有两个专用的日期格式化程序,ISO8601DateFormatter
用于将ISO8601字符串转换为Date
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let createdAtDate = isoFormatter.date(from: "2019-08-12T10:34:05.000Z")
let startedOn = "2019-08-12T10:32:18.000Z"
let stopedOn = "2019-08-12T10:34:05.000Z"
let startedOnDate = isoFormatter.date(from: startedOn)!
let stopedOnDate = isoFormatter.date(from: stopedOn)!
和DateComponentsFormatter
从开始日期和结束日期之间的差值中获取一个m:ss
字符串
let componentsFormatter = DateComponentsFormatter()
componentsFormatter.allowedUnits = [.minute, .second]
let duration = componentsFormatter.string(from: startedOnDate, to: stopedOnDate)