Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current time as string swift 3.0 [duplicate]

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

date time format.

yyyy-MM-dd HH:mm:ss

like image 908
GayashanK Avatar asked Apr 04 '17 06:04

GayashanK


2 Answers

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
like image 140
Alexandr Kolesnik Avatar answered Oct 21 '22 11:10

Alexandr Kolesnik


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()
like image 17
GayashanK Avatar answered Oct 21 '22 09:10

GayashanK