0

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

kishan
  • 203
  • 1
  • 6
  • 15

3 Answers3

3

You can change the time components when you create a new NSDate object with:

NSDate *date = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];

Answer from: https://stackoverflow.com/a/5611700/4535184


Community
  • 1
  • 1
AntonioM
  • 655
  • 9
  • 16
1

Try this

NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzzz"];
NSDate *date = [formatter dateFromString:@"2018-01-19 18:30:00 +0000"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: NSCalendarUnitDay| NSCalendarUnitHour| NSCalendarUnitMinute|NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear  fromDate:date];
[components setHour:10];
[components setMinute:0];
[components setSecond:0];
NSDate *newDate = [calendar dateFromComponents:components];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"%@",[formatter stringFromDate:newDate]);
kb920
  • 3,039
  • 2
  • 33
  • 44
  • @kishan if you want output in 24 hours format then format should be *yyyy-MM-dd HH:mm:ss* else it should be *yyyy-MM-dd hh:mm:ss a* – kb920 Mar 02 '17 at 09:59
1

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]);
Patel Jigar
  • 2,141
  • 1
  • 23
  • 30