0

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.

yong ho
  • 3,892
  • 9
  • 40
  • 81

1 Answers1

0

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]);
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • Correct. But how do I get the right NSDate from it? – yong ho Jun 08 '15 at 01:29
  • The date *itself* does not change. It is just how you view it. If you change the time zone or daylight savings setting of the *formatter*, the *displayed* displayed date will be different but not the *actual* date. – Mundi Jun 08 '15 at 08:10
  • So there is no way to get the actual NSDate from it, right? Even I set the correct time zone and daylight saving setting, right? – yong ho Jun 09 '15 at 07:05
  • No. You are getting the actual date from it in your desired time zone. – Mundi Jun 09 '15 at 19:48
  • Thanks, I got it. No matter what the NSDate shows, it's the actual date. – yong ho Jun 11 '15 at 11:27