如何在 iOS 中获取两个日期之间的差值?

iosapps/applicationsmobile development更新于 2026/2/13 10:52:17

获取两个日期之间的差值很容易。您应该知道如何在日期之间进行操作。

我们将使用 DateFormatter 类来格式化日期。

DateFormatter 的实例创建 NSDate 对象的字符串表示形式,并将日期和时间的文本表示形式转换为 NSDate 对象。

您可以在此处阅读更多相关信息

 https://developer.apple.com/documentation/foundation/dateformatter

我们还将使用日历结构,Apple 提供了详细的文档。

 https://developer.apple.com/documentation/foundation/calendar

现在就开始吧。

打开 Xcode,新建 Playground。

复制以下代码

import UIKit
// 创建 DateFormatter 和 Calendar 对象
let formatter = DateFormatter()
let calendar = Calendar.current
// 指定格式
formatter.dateFormat = "dd-MM-yyyy"
// 指定开始日期
let startDate = formatter.date(from: "10-08-2018")
// 指定结束日期
let endDate = formatter.date(from: "23-09-2019")
print(startDate!)
print(endDate!)
let diff = calendar.dateComponents([.day], from: startDate!, to: endDate!)
// 打印两个日期之间的差异
print(diff)

相关文章