2016-10-27 62 views
-1

我正在使用以下代碼獲取當前日期並對其進行格式設置。 但看到錯誤「無法調用initiliazer類型‘日期’不帶參數的」無法在Swift 3.0中獲取當前日期

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 

截圖

enter image description here

+0

在哪裏這是代碼嗎? – rmaddy

+0

您的項目可能已經定義了另一個名爲「Date」的類?這是從Swift 2遷移的代碼的常見問題,因爲當時Apple的版本被稱爲「NSDate」。 –

+0

從ViewDidLoad()調用getCurrentDate() – Badrinath

回答

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

我試着把viewDidLoad放在裏面,還是一樣的問題。在 – Badrinath

+0

上面附加的屏幕截圖解決了這個問題,又有了名爲Date的另一個類。 – Badrinath

0

我建議你用這種方式來格式化樣式(SWIFT 3):

formatter.dateStyle = DateFormatter.Style.full 
formatter.timeStyle = DateFormatter.Style.long 

在這種情況下一個日期作爲字符串與您的locale:

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