10

This is my JSON data

{
    "service_facility_id": 1,
    "service_id": 4,
    "facility_name": "Fitting",
    "charge_per_min": 40,
    "charge_per_km": 50
},
{
    "service_facility_id": 10,
    "service_id": 4,
    "facility_name": "Health Care",
    "charge_per_min": 100,
    "charge_per_km": 0
}

Currently i'm using Get method to print specific JSON output in X Code. So i managed to Minute(charge_per_min) value . But I want to display in a label in HH(Hours) format, so how to convert it minute to hours formate and disply into a uilabel.. The code as below.

if let con = country["charge_per_km"] as? Int {              
      print("+++++\(con) +++ ")
      self.chargPerKm.append(con)

      print(self.chargPerKm)

      let encodedArray : NSData = NSKeyedArchiver.archivedData(withRootObject:self.chargPerKm) as NSData
      //Saving
      let defaults = UserDefaults.standard
      defaults.setValue(encodedArray, forKey:"charge_per_km")
      print("\(UserDefaults.standard.value(forKey: "charge_per_km")!)")
      defaults.synchronize()
      print(defaults)                   
}

any one help me.

JuicyFruit
  • 2,638
  • 2
  • 18
  • 35
mike kumawat
  • 165
  • 1
  • 2
  • 8
  • Take a look at this, see if helps: http://stackoverflow.com/questions/26794703/swift-integer-conversion-to-hours-minutes-seconds – José Neto May 19 '17 at 11:27

2 Answers2

34

try it in playground

func minutesToHoursAndMinutes(_ minutes: Int) -> (hours: Int , leftMinutes: Int) {
    return (minutes / 60, (minutes % 60))
}

let tuple = minutesToHoursAndMinutes(100)

tuple.hours  /// 1
tuple.leftMinutes /// 40
Jonas Deichelmann
  • 3,513
  • 1
  • 30
  • 45
Damyan Todorov
  • 536
  • 1
  • 6
  • 17
1

To convert from minutes to hours (could be replaced with any supported measurement values)

func calculateTime(_ timeValue: Float) -> String {
        let timeMeasure = Measurement(value: Double(timeValue), unit: UnitDuration.minutes)
        let hours = timeMeasure.converted(to: .hours)
        if hours.value > 1 {
            let minutes = timeMeasure.value.truncatingRemainder(dividingBy: 60)
            return String(format: "%.f %@ %.f %@", hours.value, "h", minutes, "min")
        }
        return String(format: "%.f %@", timeMeasure.value, "min")
    }

As an example

let value = calculateTime(50) //50 min
let value1 = calculateTime(125) // 2 h 5 min
artyom
  • 48
  • 11