[英]How to get current time in Swift?
I'm trying to get the current time, and I've done this so far: 我想要获得当前时间,到目前为止我已经完成了这个:
let date = NSDate()
let calender = NSCalendar.currentCalendar()
let components = calender.component([.Hour, .Minute], fromDate: date)
And I then try to get the hour of the components 然后我尝试获取组件的小时
let hour = components.hour
This give me "Value of type "Int" has no member 'hour'" . 这给了我“类型的价值”Int“没有成员'小时'” 。 Any suggestions?
有什么建议么?
Change 更改
let components = calender.component([.Hour, .Minute], fromDate: date)
to 至
let components = calender.components([.Hour, .Minute], fromDate: date)
NSCalendar.component(_:fromDate:)
returns a single component of a date, as an Int
. NSCalendar.component(_:fromDate:)
返回日期的单个组件,作为Int
。 So your components
variable is actually of type Int
. 所以你的
components
变量实际上是Int
类型。 Passing multiple units to component(_:fromDate:)
(as you are doing) is undefined. 将多个单元传递给
component(_:fromDate:)
(正如您所做的那样)是未定义的。
Try this instead: 试试这个:
let components = calender.components([.Hour, .Minute], fromDate: date)
Note that the first part of the method name here is components
, not component
. 请注意,此处方法名称的第一部分是
components
,而不是component
。
Also, you might want to change your calender
variable to calendar
, since that is the correct spelling. 此外,您可能希望将
calender
变量更改为calendar
,因为这是正确的拼写。
swift 4 迅速4
let hh2 = (Calendar.current.component(.hour, from: Date()))
let mm2 = (Calendar.current.component(.minute, from: Date()))
let ss2 = (Calendar.current.component(.second, from: Date()))
print(hh2,":", mm2,":", ss2)
output: ---> 9 : 10 : 55
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.