thalacker
thalacker

Reputation: 2827

how to convert a date string into a NSDate type swift

I am attempting to take a string in the format dd/mm/yyyy and convert it to an NSDate so I can store a birthday. The day, month, and year are validated to be a real date (not in the future either) so I know that they are correct. They are entered as text fields by the user and I suppose I could make the dateString any format I want it that would be helpful.

let day = dayTextField.text
let month = monthTextField.text
let year = yearTextField.text
let dateString = "\(day)/\(month)/\(year)"
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "dd/MM/yyyy"

let birthdate: NSDate = dateFormatter.date(from: dateString) as NSDate

My problem is with the last line when I attempt to cast my date string to an NSDate, I get the following error:

'Date?' is not convertible to 'NSDate'; did you mean to use 'as!' to force downcast?

I could force cast after "(from: dateString)" but I didn't think that would be the right thing to do.

Any help and insight you can provide would be greatly appreciated! Thank you

Upvotes: 6

Views: 5066

Answers (2)

Sweeper
Sweeper

Reputation: 270980

It is way easier for both you and the user if you let the user choose a date from a UIDatePicker. This has a lot of advantages:

  • The user don't have to type in three text fields
  • You can get the selected date via the date property. You don't need all these formatters and stuff
  • You can set a maximum date that the user can select via the maximumDate property. This way you don't have to check if it is in the future manually. Just set maximumDate to now.
  • The date picker will use different formats depending on the user's locale. You don't need to worry about it at all.

Just remember to set the datePickerMode to .date!

As for the conversion to NSDate, you can do this easily by this expression:

datePicker.date as NSDate

If you insist on using three text fields, you can do this:

dateFormatter.date(from: dateString) as NSDate? // note that this produces an optional

Upvotes: 3

Mahesh Dangar
Mahesh Dangar

Reputation: 804

your code is working fine so check the valus in your textfield that are coming in ur variable or not

  let day = "10"
    let month = "12"
    let year = "2018"
    let dateString = "\(day)/\(month)/\(year)"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    let birthdate: NSDate = dateFormatter.date(from: dateString) as! NSDate
    print(birthdate)

but i would suggest you to use Date instead of NSDate.

Upvotes: 0

Related Questions