Search code examples
iosobjective-cnsdate

Issue with NSDate


I am having a NSDate object in format as 2018-01-19 18:30:00 +0000. Now i want to change only the time components. After changing the time components the NSDate Object would be as 2018-01-19 10:00:00. I did tried various solution but nothing worked. If any one have any solution regarding this issue help out. Thank you in advance

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: NSCalendarUnitYear| NSCalendarUnitMonth| NSCalendarUnitDay fromDate:date];

[components setHour:hour];
[components setMinute:minute];
[components setSecond:second];
NSDate *newDate = [calendar dateFromComponents:components];

another solution i tried is

  NSDate *oldDate = date; 
  unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
  NSCalendar *calendar = [NSCalendar currentCalendar];
  NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDate];
  comps.hour   = 10;   
  comps.minute = 00;
  comps.second = 00;
  NSDate *newDate = [calendar dateFromComponents:comps];

Every time i get output is next date of input date


Solution

  • Here is your code just add dateformater to formate the date

    NSDate *oldDate = [[NSDate alloc]init];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDate];
    comps.hour   = 10;
    comps.minute = 00;
    comps.second = 00;
    NSDate *newDate = [calendar dateFromComponents:comps];
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    formater.dateFormat = @"YYYY-MM-dd hh:mm:ss";
    NSLog(@"New Date : %@",[formater stringFromDate:newDate]);