Search code examples
swifttimeswift3nscalendar

Get current time as string swift 3.0


How to get current time as a String (not as Date)

date time format.

yyyy-MM-dd HH:mm:ss


Solution

  • This is the way I figure it out.

       // Get today date as String
    
            func getTodayString() -> String{
    
                    let date = Date()
                    let calender = Calendar.current
                    let components = calender.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
    
                    let year = components.year
                    let month = components.month
                    let day = components.day
                    let hour = components.hour
                    let minute = components.minute
                    let second = components.second
    
                    let today_string = String(year!) + "-" + String(month!) + "-" + String(day!) + " " + String(hour!)  + ":" + String(minute!) + ":" +  String(second!)
    
                    return today_string
    
                }
    
            let today : String!
    
            today = getTodayString()