-1

I am using below code to get current date and formatting it. But seeing error "Cannot invoke initiliazer for type "Date" with no arguments"

    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

screenshot

enter image description here

Badrinath
  • 325
  • 1
  • 7
  • 25

3 Answers3

0

You may not be placing the code in the correct location. Make sure it is inside a function of some kind. You can could even place this inside 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)
}
MwcsMac
  • 6,810
  • 5
  • 32
  • 52
0

I suggest you use this approach to Formatter Style (Swift 3):

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

In this case for a date as string with your 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) 
thinkswift
  • 528
  • 1
  • 5
  • 15
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
Deepak Tagadiya
  • 2,187
  • 15
  • 28