iosnsdatecomponentsnsdatepicker

How to set hour/minute/second in NSDateComponents with a string?


I am having a small problem with NSDateComponents.

What I have right now looks like this: [2014-8-08 08:00:00] because I'm using the current time initially (using [NSDate date]), and then setting the hours, minutes and seconds manually to something else through comps.

My objective is to separate the date from the time using a string. I still want to be able to use the current time, but when it comes to [comps set Hour/Minute/Second], I want to set them all using a string.

The string would be formatted like this: (06:00:00).

I need to set this as my default choice when opening NSDatePicker. So, it should look like [2014-8-08 06:00:00] initially when selecting a date.

Is there any way that I can set the hour/minute/second through a string?

I HAVE to use a string. the 06:00:00 resembles a MYSQL query for when a store opens it's doors. I am working with hundreds of stores. Each store has different opening times. Thanks

Franco

startTimeDatePicker.datePickerMode = UIDatePickerModeDateAndTime;
NSDate *now = [NSDate date];
startTimeDatePicker.maximumDate = now;


NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
[comps setHour:8];
[comps setMinute:0];
[comps setSecond:0];

NSDate *dateFromComps = [calendar dateFromComponents:comps]; 

Solution

  • This is the correct answer. You must separate the string individually, and input them into the components.

    NSArray *results = [storeOpen componentsSeparatedByString:@":"];
    if ([results count] == 3) {
        NSLog(@"1 - %d", [[results objectAtIndex:0] intValue]);
        NSLog(@"2 - %d", [[results objectAtIndex:1] intValue]);
        NSLog(@"3 - %d", [[results objectAtIndex:2] intValue]);
    
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
    [comps setHour:[[results objectAtIndex:0] intValue]];
    [comps setMinute:[[results objectAtIndex:1] intValue]];
    [comps setSecond:[[results objectAtIndex:2] intValue]];
    
    
    NSDate *dateFromComps = [calendar dateFromComponents:comps];