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 !

1
  • Consider DateComponentsFormatter Commented Nov 9, 2016 at 17:34

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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 } 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.