-1

There are many issues similar to mine, but something goes wrong. Why function setDay sets to 1 day less? Where did I go wrong?

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *today = [NSDate date];
NSLog(@"today date = %@", today);
NSDateComponents *components = [calendar components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear ) fromDate:today];
[components setDay:1];
NSLog(@"modified date = %@", [calendar dateFromComponents:components]);

Log:

today date = 2016-07-04 10:01:30 +0000
modified date = 2016-06-30 21:00:00 +0000

Modified date should be 2016-07-01

3 Answers3

1

Likely it is 2016-07-01, 24:00 GMT. NSLog() prints it out for GMT, not your locale time.

See here: Unexpected value from NSDate

Community
  • 1
  • 1
Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50
1

You should add NSCalendarUnitHour in NSDateComponents like this then then you get correct date

NSDateComponents *components = [calendar components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear |NSCalendarUnitHour) fromDate:today];
kirti Chavda
  • 3,029
  • 2
  • 17
  • 29
0

Try this code:

NSDateFormatter* df = [[NSDateFormatter alloc] init];    
[df setTimeZone:[NSTimeZone defaultTimeZone]];    // your time 00:00:00
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"modified date = %@", [df stringFromDate:[calendar dateFromComponents:components]]);  // Date format NSString
Bhadresh Kathiriya
  • 3,147
  • 2
  • 21
  • 41