0

I'm trying to use the solution provided in "NSDate for first day of the month" to get the first day of month.

My code is in a NSDate category:

- (NSDate *)firstDayInMonthOfDate {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:self];
    comps.timeZone = calendar.timeZone;
    NSDate *startDate;
    [comps setDay:1];
    startDate = [calendar dateFromComponents:comps];
    return startDate;
}

This yields the last day of the previous month.... example:

self = date: 2013-11-02 22:00:00  

comps = <NSDateComponents: 0x749b4c0>
        TimeZone: Europe/Bucharest (GMT+03:00) offset 10800 (Daylight)
        Calendar Year: 2013
        Month: 11
        Leap month: no
        Day: 1 

startDate = 2013-10-31 22:00:00 +0000

So, in order to get the correct day, I have to set comps.day = 2. I just don't understand where the extra 1 is coming from.

[EDIT] I want to use the dates for collection view cells, so I would like a reliable way to get the first date of the month, eg. 2013-11-01

[EDIT] Using a NSDateFormatter to print the date gives the correct result (2013-10-31). The problem with po and NSLog is that they don't interpret the timezone properly right (2012-12-31 10pm + 3h GMT != 2013-01-01 12am) I recomend a date programming tutorial: http://rypress.com/tutorials/objective-c/data-types/dates.html

Community
  • 1
  • 1
Andrei Nagy
  • 497
  • 1
  • 4
  • 15
  • 2
    ***TIME ZONE*** -- This is (at least) the second time for this question with the past hour or two. And a dupe many times over. – Hot Licks Oct 06 '13 at 12:58
  • 1
    If you only copy&paste code you should not be surprised, if you don't understand it. – vikingosegundo Oct 06 '13 at 13:01
  • possible duplicate of [Getting date from \[NSDate date\] off by a few hours](http://stackoverflow.com/questions/8466744/getting-date-from-nsdate-date-off-by-a-few-hours) – Hot Licks Oct 06 '13 at 13:02

1 Answers1

2

Your result is correct.

NSLog(@"%@", startDate) or po startDate in the debugger always prints the date with respect to GMT, and

 startDate = 2013-10-31 22:00:00 +0000

is the same as 2013-11-01 00:00:00 in GMT+2, which is your time zone.

Note that you can simplify your code to

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startDate;
[calendar rangeOfUnit:NSMonthCalendarUnit startDate:&startDate
             interval:NULL forDate:self];
return startDate;
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382