简体   繁体   中英

How to calculate days to months, years, days in Swift?

I need to find months, years, days from given days. For example, 370 days, I need to convert to 1 year 0 month & 5 days. Days can be rounded off to the nearest month. For example, if days are less than 15, that should go to 0 month. If its more than 15 days, now that should go to 1 month

Assuming you know starting and/or ending date, and not just distance between them, you can use this:

date​Components(_:​from:​to:​)

Returns the difference between two dates.

Declaration

 func dateComponents(_components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents 

Parameters

components

Which components to compare.

start

The starting date.

end

The ending date.

Example:

let calendar = Calendar(identifier: <whatever calendar you need>)
let components: DateComponents = calendar.dateComponents([.calendar, .year, .month, .day], from: startDate, to: endDate)

And then from DateComponents you get your years , months and days and what not.

func numberOfDaysInCurrentYear() -> Int {
    let calendar = Calendar.init(identifier: .gregorian)
    let interval = calendar.dateInterval(of: .year, for: Date.init())!
    let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
    return days
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM