Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving 1st day of month using NSCalendar

I execute following snippet of code:

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

NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];

The Value of firstDayOfMonthDate is = 30-4-2011 but excpeted is 1-5-2011 i.e I want first date of month of any specified date. But it gives me the last date of the previous month.

thanks in advance.

like image 393
Samyag Shah Avatar asked May 07 '11 11:05

Samyag Shah


1 Answers

Add

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

after initializing your NSCalendar.

[NSDate date] will return a date in the UTC timezone, well an absolute interval since January 1, 2001 00:00 GMT, but the NSCalendar has its timeZone set to the default timezone which may not be UTC.

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

In casual use, when fractions of a second are not important, Greenwich Mean Time (GMT) can be considered equivalent to UTC or UT1. Saying "GMT" often implies either UTC or UT1 when used within informal or casual contexts. In technical contexts, usage of "GMT" is avoided; the unambiguous terminology "UTC" or "UT1" is preferred.[3]

like image 69
Nick Weaver Avatar answered Nov 10 '22 03:11

Nick Weaver