Search code examples
swiftstringtimetimestampnsdate

How to get time from date including the "0" in Minutes?


I am using this method for getting the time in my application:

let date = Date()
let calendar = Calendar.current

let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)

let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)

timeStamp = ("\"\(hour):\(minutes)\"")
dateFull = ("\"\(day)/\(month)/\(year)\"")

print(dateFull)
print(timeStamp)

When I print out timeStamp it gives me some strange values when the "Minutes" is below 10 past the hour e.g instead of "9:03" it will print "9:3" etc. It doesn't include the 0 before the digit. Any way around this using my current method?

Thanks!


Solution

  • func convertDateToHourMin(date : Date) -> String{
            let calender = Calendar.current
            let components = calender.dateComponents([.hour,.minute,], from: date)
            var hour = String(components.hour!)
            var minute = String(components.minute!)
    
            if hour.count == 1{
                hour = "0\(hour)"
            }
    
            if minute.count == 1{
                minute = "0\(minute)"
            }
    
            return "\(hour)\(minute)"
    }
    

    or you can also write like this.

    func convertDateToHourMin(date : Date) -> String{
        let calender = Calendar.current
        let components = calender.dateComponents([.hour,.minute,], from: date)
        let dateInString  = String(format: "%02d:%02d", Int(components.hour!) , Int(components.minute!))
        return dateInString
    }