Get current time as string swift 3.0

GayashanK picture GayashanK · Apr 4, 2017 · Viewed 30.7k times · Source

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

date time format.

yyyy-MM-dd HH:mm:ss

Answer

GayashanK picture GayashanK · Apr 4, 2017

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()