How to convert days into human-readable years, months and days in Swift

2 Answers

0 votes
import Foundation

struct YMD {
    let years: Int
    let months: Int
    let days: Int
}

func splitDays(_ totalDays: Int) -> YMD {
    let calendar = Calendar.current
    let start = DateComponents(calendar: calendar, year: 1970, month: 1, day: 1).date!
    let end = calendar.date(byAdding: .day, value: totalDays, to: start)!

    let components = calendar.dateComponents([.year, .month, .day], from: start, to: end)

    return YMD(
        years: components.year ?? 0,
        months: components.month ?? 0,
        days: components.day ?? 0
    )
}



let r = splitDays(452)

print("\(r.years) years, \(r.months) months, \(r.days) days")



/*
run:

1 years, 2 months, 28 days

*/

 



answered Jan 1 by avibootz
0 votes
import Foundation

struct SimpleYMD {
    let years: Int
    let months: Int
    let days: Int
}

func splitDays(_ total: Int) -> SimpleYMD {
    var days = total

    let years = days / 365
    days %= 365

    let months = days / 30
    days %= 30

    return SimpleYMD(years: years, months: months, days: days)
}


let r = splitDays(452)

print("\(r.years) years, \(r.months) months, \(r.days) days")



/*
run:

1 years, 2 months, 27 days

*/

 



answered Jan 1 by avibootz

Related questions

...