Swift – 获取当地日期时间

我怎么可能在swift中获得本地日期时间?

我的代码

let last_login = String(NSDate.date()) 

请指教。 谢谢。

更新: Xcode 8.2.1•Swift 3.0.2

您还可以使用Date方法description(with locale: Locale?)来获取用户的本地化时间描述:

Date的字符串表示forms,使用给定的语言环境,或者locale参数为nil,采用国际格式YYYY-MM-DD HH:MM:SS±HHMM,其中±HHMM表示以小时和分钟为单位的时区偏移量UTC(例如,“2001-03-24 10:45:32 +0600”)。

description(使用locale:Locale?)

 Date().description(with: .current) // "Monday, February 9, 2015 at 05:47:51 Brasilia Summer Time" 

使用NSDateFormatter,通过设置格式

 let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "hh:mm" println(dateFormatter.stringFromDate(NSDate())) 

或风格

 dateFormatter.dateStyle = .NoStyle dateFormatter.timeStyle = .MediumStyle 

我已经找到了答案。

 let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy HH:mm" let dateInFormat = dateFormatter.stringFromDate(NSDate()) 
 let expiryDate: Date = ... let localizedDateString = DateFormatter.localizedString(from: expiryDate, dateStyle: .medium, timeStyle: .short) 

“2017年9月10日,14:37”

您必须使用NSDateFormatter

 let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMMM dd, yyyy HH:mm" dateFormatter.locale = "en" // Change "en" to change the default locale if you want let stringDate = dateFormatter.stringFromDate(date) 

Leo的答案非常好。 我只想添加一种方法将其用作计算属性。

  var currentTime: String { get { return Date().description(with: Locale.current) } } 

像这样使用它:

 print(currentTime) 

获取当前日期和时间

 let currentDate = Date() print(currentDate) //this will return current date and time 

但这将是日期类型,以将日期转换为字符串

 let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" //give the formate according to your need let dateStr = dateFormatter.string(from: currentDate) //which will give the string of current date and time in required dateformate