Getting 1st day of a month using NSCalendar

I am executing the following code snippet:

NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]]; 
[comp setDay:1]; 

NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];

FirstDayOfMonthDate = 30-4-2011, but excpeted is 1-5-2011. I want the first date of the month of any given date. But that gives me the last date of the previous month.

early.

+5
source share
1 answer

Add

[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

after initializing your NSCalendar.

[NSDate date] will return the date to the UTC time zone, as well as the absolute interval from January 1, 2001, 00:00 GMT, but NSCalendar has its own time zone set to the default time zone, which may not be UTC.

UTC is "the same" as UTC, a quote from Wikipedia:

, , , (GMT) UTC UT1. "GMT" UTC, UT1, . "GMT"; "UTC" "UT1" . [3]

+10

All Articles