13

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

date time format.

yyyy-MM-dd HH:mm:ss

GayashanK
  • 1,195
  • 2
  • 13
  • 27
  • 1
    If you want time interval in seconds, why you need to convert to String first? You can use DateFormatter to covert Date into String – Anil Varghese Apr 04 '17 at 06:20
  • Thanks. Just in my case I received only time in hh:mm a format as string. How can I get it in yyyy-MM-dd HH:mm:ss format and convert into seconds – GayashanK Apr 04 '17 at 06:28
  • 1
    all you need to get the timeIntervalSince1970 for now is `let timeIntervalSince1970 = Date().timeIntervalSince1970` – Leo Dabus Apr 04 '17 at 06:30

2 Answers2

21

To get time as String you should use DateFormatter, something like this, sorry if there some mistakes, I wrote it right here

let dateFormatter : DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = Date()
let dateString = dateFormatter.string(from: date)
let interval = date.timeIntervalSince1970
Alexandr Kolesnik
  • 1,929
  • 1
  • 17
  • 30
17

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()
GayashanK
  • 1,195
  • 2
  • 13
  • 27
  • It's much better to use a `DateFormatter` than getting all of the date components and building your own string. – rmaddy Jul 31 '18 at 05:36
  • 1
    To get something even simpler, based on the use of textfield, as far as you link a Date Formatter, you can simply write `mytextfield.objectValue = Date()`. – Jerome Nov 26 '18 at 15:13