Sylar
Sylar

Reputation: 12072

Remove Optional string for date in UIDatePicker

Happy New Year, all!

How do I get a datePicker text to show like this Jan 1, 2017 instead of 2017/1/1? In my PlayGround, it looks as expected but in my simulator or console, it looks not expected.

// createDatePicker():
datePicker.datePickerMode = .date

// donePressed():
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "mm/dd/yyyy"
let fromString = dateFormatter.string(from: datePicker.date)
let date = dateFormatter.date(from: fromString) // I dont need time but got Jan 1, 2017, 12:00 AM in playground
datePickerText.text = "\(date)"
print("\(date)") // in console: Optional(2017-1-1 00:00:00 +0000)

I need to get rid of the Optional() but not sure how to convert Date! to String!. How to achieve getting the text to be Jan 1, 2017?

Upvotes: 0

Views: 479

Answers (3)

Anand Nimje
Anand Nimje

Reputation: 6251

In your code you converting Date to date String: -

let fromString = dateFormatter.string(from: datePicker.date)
let date = dateFormatter.date(from: fromString) //Avoid this line in your code

then no need to change again date string into date try below code: -

let formatter = DateFormatter()
formatter.dateFormat = "MMM d, yyyy" //Date Formatting
let date = formatter.string(from: datePicker.date)
datePickerText.text = date
print(date)

Output:-

 Jan 1, 2017

Upvotes: 1

ronatory
ronatory

Reputation: 7324

Just format your date how you want it to be, like this:

dateFormatter.dateFormat = "MMM d, yyyy"
let fromString = dateFormatter.string(from: datePicker.date)
print(fromString) // Jan 1, 2017

Upvotes: 0

Niroj
Niroj

Reputation: 1114

You can try this!

   let formatter = NSDateFormatter()
formatter.dateformat = "MMMM dd,YYYY"

if there is any label to which your are trying to show the date format then,

label.text = formatter.stringFromDate(datepicker.date)

Upvotes: 0

Related Questions