2015-02-09 68 views
8

我可以如何获得本地日期时间?Swift - 获取当地日期时间

我的代码

let last_login = String(NSDate.date()) 

请指点。谢谢。

+1

找到了一个很棒的网站来帮助找出你的格式字符串: http://nsdateformatter.com/ – Eric 2016-06-30 11:56:57

回答

4

我已经找到了答案。

let dateFormatter = NSDateFormatter() 
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm" 
let dateInFormat = dateFormatter.stringFromDate(NSDate()) 
+2

如何获取日期对象不是字符串 – 2017-03-26 03:39:41

3

使用NSDateFormatter,通过设置格式

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

或样式

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

你必须使用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) 
23

更新:的Xcode 8.2.1•斯威夫特3.0 .2

您也可以使用日期的方法描述(:区域设置),以获得用户的本地化时间描述:

日期的字符串表示,使用给定的语言环境,或者如果区域 说法是零,采用国际格式YYYY-MM-DD HH:MM:SS ±HHMM,其中,±HHMM表示以小时为单位的时区偏移量,距离UTC为 分钟(例如,“2001-03-24 10:45:32 +0600 “)。

descriptionWithLocale

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

你统治。为什么不是每个人都这样做? – ScottyBlades 2017-11-27 19:30:29

2
let expiryDate: Date = ... 
let localizedDateString = DateFormatter.localizedString(from: expiryDate, dateStyle: .medium, timeStyle: .short) 

“2017年9月10日,14时37分”

0

狮子座的答案是相当不错的。我只是想添加一种方法将其用作计算属性。

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

使用它,像这样:

print(currentTime) 
1

要获取当前日期和时间

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 
+0

dateFormatter.dateFormate? dd-MM-yyy HH:mm? – 2017-12-26 04:06:11

+0

谢谢回答更新 – 2017-12-26 06:09:36