2016-10-27 2 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

вызов getCurrentDate() из ViewDidLoad() – 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

Я предлагаю вам использовать этот подход к Formatter Style (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) 
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 
Смежные вопросы