I am trying to get the beginning date of a month.
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"begining of month: %@ from today", [self beginningOfMonth:[NSDate date]]);
}
- (NSDate *)beginningOfMonth:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.locale = [NSLocale currentLocale];
calendar.timeZone = [NSTimeZone defaultTimeZone];
calendar.firstWeekday = 2;
NSDateComponents *componentsCurrentDate = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitWeekOfMonth fromDate:date];
NSDateComponents *componentsNewDate = [NSDateComponents new];
componentsNewDate.year = componentsCurrentDate.year;
componentsNewDate.month = componentsCurrentDate.month;
componentsNewDate.weekOfMonth = 1;
componentsNewDate.weekday = calendar.firstWeekday;
return [calendar dateFromComponents:componentsNewDate];
}
But the console outputs is 2015-06-05 10:41:54.544 Test[1119:25066] begining of month: 2015-05-31 16:00:00 +0000
I just looked the calendar, it should be 2015-06-01 but it shows 2015-05-31. And I did set firstWeekday to 2, so it's Monday.
It seems you are getting the right result. Depending on the time zone of your Xcode installation, the console will output a different date.
Try using a date formatter in NSLog
.
NSDateFormatter *f = [[NSDateFormatter alloc] init];
NSDate *firstMonday = [self beginningOfMonth:[NSDate date];
NSLog(@"First Monday of month: %@", [f stringFromDate:firstMonday]);