Ali
Ali

Reputation: 9994

Default Date for UIDatePicker in iOS

I am new in iOS development. I have this ViewController in my Storyboard (includes a UIDatePicker and a bar button):

enter image description here

I followed Data Cell to call my DatePicker. When user click on a button in the page PickerDate pops up with a done bar button on the navigation bar:

enter image description here

The problem is it shows just the current date as default. Nothing changes when I set it from Properties:

enter image description here

Do you know how can I fix it? (by setting up the properties or programmatically).

Upvotes: 3

Views: 15405

Answers (3)

King-Wizard
King-Wizard

Reputation: 15694

In Swift:

let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
calendar.timeZone = NSTimeZone(name: "UTC")!
let components: NSDateComponents = NSDateComponents()
components.year = 1980
components.month = 1 
components.day = 1
let defaultDate: NSDate = calendar.dateFromComponents(components)!
self.dateOfBirthUIDatePicker.date = defaultDate

Upvotes: 4

ICL1901
ICL1901

Reputation: 7778

Great answers above - Here's the Swift3 (Feb 17) version:

let calendar: NSCalendar = NSCalendar(calendarIdentifier:  .gregorian)!
calendar.timeZone = NSTimeZone(name: "UTC")! as TimeZone
let components: NSDateComponents = NSDateComponents()
components.year = 1980
components.month = 1
components.day = 1
let defaultDate: NSDate = calendar.date(from: components as DateComponents)! as NSDate
self.datePicker.date = defaultDate as Date

Upvotes: 2

Ali
Ali

Reputation: 9994

I did it programmatically in this way :

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:1980];
[components setMonth:1];
[components setDay:1];
NSDate *defualtDate = [calendar dateFromComponents:components];
pickerView.date = defualtDate;

But still don't know why it doesn't work by setting up the properties. Any help?

Upvotes: 9

Related Questions