小编典典

使用Swift 3和XCode 8在数周和数天内的2个日期之间的差异

swift

我正在尝试计算几周和几天的两个日期(一个是当前日期,另一个是来自日期选择器)之间的差异,然后将结果显示在标签上,这就是我到目前为止所做的,我感谢经验丰富的开发人员的帮助这里!

let EDD = datePicker.date
let now = NSDate()

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .short
formatter.allowedUnits = [.day]
formatter.maximumUnitCount = 2

let string = formatter.string (from: now as Date, to: EDD)

label.text = string

阅读 254

收藏
2020-07-07

共1个答案

小编典典

您可以使用CalendardateComponents(_:from:to:)找到2个日期之间的差异所需的单位。

例:

let dateRangeStart = Date()
let dateRangeEnd = Date().addingTimeInterval(12345678)
let components = Calendar.current.dateComponents([.weekOfYear, .month], from: dateRangeStart, to: dateRangeEnd)

print(dateRangeStart)
print(dateRangeEnd)
print("difference is \(components.month ?? 0) months and \(components.weekOfYear ?? 0) weeks")


> 2017-02-17 10:05:19 +0000
> 2017-07-10 07:26:37 +0000
> difference is 4 months and 3 weeks

let months = components.month ?? 0
let weeks = components.weekOfYear ?? 0
2020-07-07