Pregunta

I am using a UIPickerView to display hours to choose from, which wants to go from 00:00 through to 23:00, however I am obviously doing something wrong as I am getting 11:58 through to 10:58. Here is what I am doing:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSDateComponents *dateComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
                                                   fromDate:[NSDate date]];
    [dateComponents setHour:row];
    [dateComponents setMinute:0];
    [dateComponents setSecond:0];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];

    return [dateFormatter stringFromDate:[calendar dateFromComponents:dateComponents]];
}

Any help would be much appreciate.

Thanks, Nick

¿Fue útil?

Solución 2

@Larme gave me the answer required (setting a time zone for the NSDateFormatter).

Otros consejos

I can't see any reason to use a date formatter inside your picker delegate method. The number of hours and minutes in a day are fixed. Why not just present the user with a two column picker providing hours in one and minutes in the other.

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [NSString stringWithFormat:@"%02d", row];
}

Here is what your picker data source methods would look like.

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    // Two picker columns, one for hours, one for minutes
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return 24;
        case 1:
            return 60:
    }
}

Then, when your user is done picking, build your date based on what they chose.

- (IBAction)didTapDonePickingButton:(id)sender
{
    NSInteger hour = [_pickerView selectedRowInComponent:0];
    NSInteger minute = [_pickerView selectedRowInComponent:1];

    // Build out your date here...
}

Better Yet, did you know you can just use a UIDatePicker and set its mode to "Time" in interface builder.

enter image description here

This will give you just hours and minutes. Like this:

enter image description here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top