sách gpt4 ăn đã đi

ios - 以年、月和日期格式计算日期 ios 之间的持续时间

In lại 作者:搜寻专家 更新时间:2023-10-30 21:49:13 25 4
mua khóa gpt4 giày nike

我是 swift 编程的新手,我还没有成功找到代码来找出两个日期之间的年、月和日差异。我尝试了以下代码,但没有成功

let form = NSDateComponentsFormatter()
form.maximumUnitCount = 2
form.unitsStyle = .Full
let s = form.stringFromTimeInterval( date2.timeIntervalSinceReferenceDate - date1.timeIntervalSinceReferenceDate)

đi vào

Date1 = "12/March/2015"

Date2 = "1/June/2015"

输出:x年y月z天

请多多指教

câu trả lời hay nhất

我们可以在 Swift 2.0 中使用这个函数

func yearsBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()

let components = calendar.components([.Year], fromDate: startDate, toDate: endDate, options: [])

return components.year
}

您可以像我在此函数中返回năm 那样返回任何内容。这将返回两个日期之间的年数。
您可以只写月、日等,以便分别以月和日计算两个日期之间的差异。

biên tập

Swift 3.0 及更高版本

func yearsBetweenDate(startDate: Date, endDate: Date) -> Int {

let calendar = Calendar.current

let components = calendar.dateComponents([.year], from: startDate, to: endDate)

return components.year!
}

关于ios - 以年、月和日期格式计算日期 ios 之间的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33780184/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress