Search code examples
iosobjective-cnsdatensdateformatternsdatecomponents

Get current month date in date components


I am getting NSDateComponents of date 2018-06-01 00:00:00 +0000 like this

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth|NSCalendarUnitYear |NSCalendarUnitHour | NSCalendarUnitMinute fromDate:date];
[components setTimeZone:[NSTimeZone timeZoneWithAbbreviation: @"UTC"]];
 NSInteger month =[components month];

When I print the value of components , I get this value.

    TimeZone: GMT (GMT) offset 0
    Calendar Year: 2018
    Month: 5
    Leap month: no
    Day: 31
    Hour: 21
    Minute: 0

My expected out put should be

    TimeZone: GMT (GMT) offset 0
    Calendar Year: 2018
    Month: 6
    Leap month: no
    Day: 1
    Hour: 0
    Minute: 0

How can I get the value of month correctly?


Solution

  • When you use NSCalendar components:fromDate: the results are based on the calendar's current timezone which defaults to the user's local timezone.

    Your attempt to set the resulting components' timeZone doesn't alter the current components. That would only affect how the components would be interpreted if you used the components to create a new NSDate.

    Assuming your goal is to get the components of date in UTC time and not in local time, then you need to set the calendar's timeZone before getting the components from date.

    NSDate *date = // your date
    NSCalendar *calendar = NSCalendar.currentCalendar;
    calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    NSDateComponents *components = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:date];
    NSLog(@"UTC Components: %@", components);
    

    But keep in mind that you must understand which timezone you really want here. Be sure you really want the UTC timezone. Don't use UTC just because it matches the output of NSLog(@"Date: %@", date);. That log shows the date in UTC time.