Get current time as string swift 3.0 [duplicate]

半腔热情 提交于 2019-11-27 17:55:08

问题


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

date time format.

yyyy-MM-dd HH:mm:ss


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/43199635/get-current-time-as-string-swift-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!