我使用下面的代码来获取当前日期并格式化它。 但看到错误"无法调用initiliazer类型"日期"没有参数"
let currentDateTime = Date()
// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
// get the date time String from the date object
formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM
截图
答案 0 :(得分:0)
您可能无法将代码放在正确的位置。确保它在某种功能内。您甚至可以将其放在viewDidLoad()
内。
override func viewDidLoad() {
super.viewDidLoad()
let currentDateTime = Date()
// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
// get the date time String from the date object
let mytime = formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM
print(mytime)
}
func getcurrentDate() {
let currentDateTime = Date()
// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
// get the date time String from the date object
let mytime = formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM
print(mytime)
}
答案 1 :(得分:0)
我建议你使用这种方法来格式化样式(Swift 3):
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.long
在这种情况下,日期为您的语言环境的字符串:
let currentDate = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "----your locale here----")
formatter.dateStyle = DateFormatter.Style.full
let myDate = todayFormatter.string(from: currentDate)
print(myDate)
答案 2 :(得分:0)
swift 4
==> Getting iOS device current time:-
let hh1 = Calendar.current.component(.hour, from: Date())
let mm1 = Calendar.current.component(.minute, from: Date())
let ss1 = Calendar.current.component(.second, from: Date())
print(hh1, ":", mm1, ":", ss1)
output: ---> 11 : 10: 25