NSDate returns invalid date in first month

My application used the [NSDate date] function to get the current date. His work is terminated on days other than the 1st of each month during AM . ie Follow these steps:

  • Set the system date from 01 to June 2011 and the time between 00:00 and 5:00 in the morning.
  • Use the following code:
    NSLog(@"Current Date :: %@",[NSDate date]);

O / P is :: Current date :: 2011-05-31 19:40:21 +0000

Desired O / P: Current Date :: 2011-06-01 00: 00: 0 (i.e. set time) +0000

Also from 6 in the morning it works great.

What is the reason for this?

Actually I don’t want NSDate in string format, but what I want is an NSDate date object corresponding to the 1st date of the current month. Why am I using the following code snippet:

NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit 
| NSDayCalendarUnit) fromDate:[NSDatedate]];

[comp setDay:1];     

NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];

[gregorian release];

return firstDayOfMonthDate;

Since [NSDate date] returns an invalid date, the components also contain an invalid date. The above code works for all senario, except for senario, which I posted at the beginning of this thread. What should I do?

+5
source share
2 answers

Finally, the solution was:

, NSDate , Apple , NSDate -description, NSLog, GMT + 0 . ( , - , , NSDate -description, ...)

: NSDateFormatter . -description.

+2

iOS 4.2? , - , , , . , iOS 4.0, :

Current Date :: 2011-07-06 10:43:38 -0400

iOS 4.2, :

Current Date :: 2011-07-06 14:44:18 +0000

SO, :

NSDate iOS 4.2

NSString, , , :

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString *result = [formatter stringFromDate:[NSDate date]];
[formatter release];
NSLog(@"Current Date v2 :: %@",result);
0

All Articles