Crystal
Crystal

Reputation: 29518

Creating NSDate from current date is incorrect

I'm sure I'm doing this wrong, but I basically want to create something similar to Apple's alarm clock. So I have a UIDatePicker that shows the hours and minutes only. My plan is to grab the hour and minute from the UIDatePicker, then create a UILocalNotification for that hour and minute for the current date or next date depending on if the alarm is available for that day or not. So what I try to do when my view loads is this:

[self.alarmsDatePicker addTarget:self action:@selector(datePickerDidSelect:) forControlEvents:UIControlEventValueChanged];
    [self.alarmsDatePicker setDate:[NSDate date]];

    // Get the current calendar
    self.calendar = [NSCalendar currentCalendar];
    self.dateFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;

    // Get the time portion of the datePicker's date
    NSDateComponents *timeComponentsSelectedDate = [_calendar components:_dateFlags fromDate:self.alarmsDatePicker.date];
    NSDate *timeOnlySelectedDate = [_calendar dateFromComponents:timeComponentsSelectedDate];
    self.startDate = timeOnlySelectedDate;

What I don't understand when I step through the code is, the datePicker gets the current time to start correctly. But when I get to timeOnlySelectedDate, the date is 2001-01-01. Why is that? Thanks in advance.

Upvotes: 0

Views: 153

Answers (1)

Eric Qian
Eric Qian

Reputation: 2256

Because your _dateFlags only include hour and minute. You should set your _dateFlags like this: self.dateFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit.

Upvotes: 1

Related Questions