2

i've some issue to found a proper solution in swift3 to do this :

I have a date like 10h20m. When my hours are under 10 it will be "5h30". I want to out "05h30".

class func getTime(_ user: SUser) -> String {
    let currentDate = Date()
    let firstDate = user.firstDate
    let difference = firstDate?.timeIntervalSince(now)

    let hours = String(Int(difference!) / 3600)
    let minutes = String(Int(difference!) / 60 % 60)

    let time = "\(hours)h\(minutes)m"
    return time
}

if someone have an idea how do that simply et properly thank you !

Makaille
  • 1,636
  • 2
  • 24
  • 41

3 Answers3

2

You can do something like this

class func getTime(_ user: SUser) -> String {
    let currentDate = Date()
    let firstDate = user.firstDate
    let difference = firstDate?.timeIntervalSince(now)

    let hours = String(Int(difference!) / 3600)
    if Int(hours)! < 10 {
        hours = "0\(hours)"
    }
    var minutes = String(Int(difference!) / 60 % 60)
    if Int(minutes)! < 10 {
        minutes = "0\(minutes)"
    }
    let time = "\(hours)h\(minutes)m"
    return time
}

or a better way

class func getTime(_ user: SUser) -> String {
    let currentDate = Date()
    let firstDate = user.firstDate
    let difference = firstDate?.timeIntervalSince(now)

    let hours = Int(difference!) / 3600
    let minutes = Int(difference!) / 60 % 60

    let time = "\(String(format: "%02d", hours))h\(String(format: "%02d", minutes))m"
    return time
}

Suggested here - Leading zeros for Int in Swift

Community
  • 1
  • 1
Rajat
  • 10,977
  • 3
  • 38
  • 55
0
class func getTime(_ user: SUser) -> String {
    let currentDate = Date()
    let firstDate = user.firstDate
    let difference = firstDate?.timeIntervalSince(now)

    var hours = String(Int(difference!) / 3600)
    if ((Int(difference!) / 3600)<10) {
       hours = "0\(hours)"
    }
    var minutes = String(Int(difference!) / 60 % 60)
    if ((Int(difference!) / 60 % 60)<10) {
       minutes =  "0\(minutes)"
    }
    let time = "\(hours)h\(minutes)m"
    return time
}
Eeshwar
  • 277
  • 3
  • 17
0

I think you would be better off with a simple formatting function that you can call inline.

Try something like

func formatHour(hour:Int) -> String {

    return (String(hour).characters.count == 1) ? "0\(hour)" : "\(hour)"
}

let hour = 5

print("\(formatHour(hour: hour))") // output "05"

You can adjust this as needed, maybe pass the string in instead and save doing the conversion in the function. could also add a guard statement to ensure that the number is within the bounds of hours, or a string is less than three characters etc.

Scriptable
  • 19,402
  • 5
  • 56
  • 72