Search code examples
swift3nsdate

Adding minutes by literals


ho could I manipulate some Int adding them as minutes and sum them? the result should be in hours and minutes just like 1:15 or 6:30.

My playground gives 1.25 but I expected 1.15

struct standardDayOfWork {

var dailyHours : Double = 0

}


var dayToUse = standardDayOfWork()


enum hourFractions : Double {

    case quarter = 15
    case half = 30
    case threeQuarter = 45
    case hour = 60
}


dayToUse.dailyHours += hourFractions.half.rawValue
dayToUse.dailyHours += hourFractions.half.rawValue

dayToUse.dailyHours += hourFractions.quarter.rawValue


var total = dayToUse.dailyHours / 60   //1.25

Solution

  • Because in the decimal system a quarter is 0.25.

    To get numeric 1.15 you could use this weird expression:

    var total = Double(Int(dayToUse.dailyHours) / 60) + (dayToUse.dailyHours.truncatingRemainder(dividingBy: 60) / 100.0)
    

    Or if you can live with a formatted "hh:mm" string I'd recommend

    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute]
    formatter.string(from: dayToUse.dailyHours * 60)