How to get NSDate day, month and year in integer format?

前端 未结 9 1058
长情又很酷
长情又很酷 2020-12-07 15:31

I want to get the day, month and year components of NSDate in integer form i.e. if the date is 1/2/1988 then I should get 1, 2 and 1988 separately as an integer

9条回答
  •  自闭症患者
    2020-12-07 16:06

    To those who just copy and paste directly from the web, like me, this is a small update for iOS 8

    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
    [components day]; //Day
    [components month];//Month
    [components year];//Year
    

    The difference is NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit have been deprecated

提交回复
热议问题