SwiftyJD
SwiftyJD

Reputation: 5451

How to set a UITextField.text to a NSDate?

I'm connecting to an API and when I get data back for dates it looks like this:

2016-07-05T21:39:17.696Z

How can I set a uitextfield.text to that date so it looks like a normal date (ie. 07/05/2016 or something similar)?

The tricky part is the NSDate is returned as a string from the API so it's not in the NSDate format to begin with.

Upvotes: 0

Views: 322

Answers (2)

Andrew McKinley
Andrew McKinley

Reputation: 1137

try:

let formatter = NSDateFormatter()
let yourDate = NSDate()
formatter.dateStyle = NSDateFormatterShortStyle
formatter.timeStyle = NSDateFormatterNoStyle
self.textfield.text = formatter.stringFromDate(yourDate)

Upvotes: 0

Jim
Jim

Reputation: 73946

A text field is only for editing freeform text, not dates. You can go one of two routes. If you intend for the user to be able to edit a date, then use a UIDatePicker to provide an interface specifically for editing dates. If you just want freeform text back, then you can convert a date to a string with NSDateFormatter.

Upvotes: 1

Related Questions