LK Phuc Nguyen LK Phuc Nguyen - 7 months ago 13
Swift Question

Converting NSDate to String gets empty object

In the app, there is a screen in which I use a

Date Picker
in mode
Date
to get the date input.

Then this screen will pass the date input in
NSDate
type to the previous screen to display as
textFiled
after a conversion to string.

func dateDetector(aDate: UIDatePicker) {

let dateFormat = NSDateFormatter()

dateFormat.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormat.timeStyle = NSDateFormatterStyle.NoStyle

dueDate = aDate.date

Answer

Building on the answer added by ryantxr

Sometimes you need to set a locale identifier when you are storing a date and retrieving it. Eg:-

{

let dateFormat = NSDateFormatter()
dateFomat.locale = NSLocale(localeIdentifier:"en_IN")
dateFormat.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormat.timeStyle = NSDateFormatterStyle.NoStyle

dueDate = aDate.date

}

when changing to string {

let dateFormat = NSDateFormatter() dateFomat.locale = NSLocale(localeIdentifier:"en_IN") dateFomat.dateStyle = NSDateFormatterStyle.MediumStyle let datestring = dteformat.stringFromDate(dueDate)

}

Hope this helps