Search code examples
iosiphoneios7nsdate

How to add current Time(HH:MM:SS) to NSDate?


I am using https://github.com/ruslanskorb/RSDayFlow to add calendar to my application.

I override the method as

// Prints out the selected date.
- (void)datePickerView:(RSDFDatePickerView *)view didSelectDate:(NSDate *)date {

    self.transactionDate = date;
    self.inputDateField.text =  [[Helper getDateFormatterForClient] stringFromDate:self.transactionDate];
    NSLog(@"transactionDate=%@", self.transactionDate);
    [self.inputDateField resignFirstResponder];

}

All I want to add is current time HH:MM:SS to the date user selects.

I have no idea how to do this, any help is greatly appreciated

UPDATE

Currently, when the date is selected, I get

2015-01-15 10:34:35.210 myapp-ios[21476:60b] transactionDate=2015-01-15 08:00:00 +0000 

Solution

  • If by "current time HH:MM:SS to the date" you mean that you want to replace the selected date's HH:MM:SS with the current HH:MM:SS, you can extract the relevant date components from the selected date, get the current datetime, extract the relevant time components, then add those components back into self.transactionDate, ex:

    // Prints out the selected date.
    - (void)datePickerView:(RSDFDatePickerView *)view didSelectDate:(NSDate *)date {
    
        self.transactionDate = date;
        self.inputDateField.text =  [[Helper getDateFormatterForClient] stringFromDate:self.transactionDate];
        NSLog(@"transactionDate=%@", self.transactionDate);
        [self.inputDateField resignFirstResponder];
    
        // Create an instance of the current calendar
        NSCalendar *calendar = [NSCalendar currentCalendar];
    
        // Break self.transactionDate into day, month, and year components
        NSDateComponents* dateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|
            NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.transactionDate];
    
        // Save transaction date with just the day, month, and year
        self.transactionDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
    
        // Get the current datetime
        NSDate *currentDate = [NSDate date];
    
        // Extract the hour, minute, and second components
        NSDateComponents *components = [calendar components:(NSCalendarUnitHour|
            NSCalendarUnitMinute|NSCalendarUnitSecond) fromDate:currentDate];
    
        // Add those hour, minute, and second components to
        // self.transactionDate
        self.transactionDate = [calendar dateByAddingComponents:components 
            toDate:self.transactionDate options:0];
    
    }