iOS 根据生日得到生肖,星座,年龄的算法

根据用户生日,得到相应的年龄,星座和生肖。有的项目中可能会用到,贴出来共享。

得到年龄,这个很简单了:

- (void)getAgeWith:(NSDate*)birthday{



    //日历

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    

    NSUInteger unitFlags = NSCalendarUnitYear;

    

    NSDateComponents *components = [gregorian components:unitFlags fromDate:birthday toDate:[NSDate  date] options:0];



    self.age.text = [NSString stringWithFormat:@"%ld岁了",[components year]+1];

}

根据月日得到星座:

//得到星座的算法

-(NSString *)getAstroWithMonth:(NSInteger)m day:(NSInteger)d{

    

    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";

    

    NSString *astroFormat = @"102123444543";

    

    NSString *result;

    

    if (m<1||m>12||d<1||d>31){

        

        return @"错误日期格式!";

        

    }

    

    if(m==2 && d>29)

        

    {

        

        return @"错误日期格式!!";

        

    }else if(m==4 || m==6 || m==9 || m==11) {

        

        if (d>30) {

            

            return @"错误日期格式!!!";

            

        }

        

    }

    

    result=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(m*2-(d < [[astroFormat substringWithRange:NSMakeRange((m-1), 1)] intValue] - (-19))*2,2)]];

    

    return [result stringByAppendingString:@""];

    

}

根据年份得到生肖:

-(NSString *)getZodiacWithYear:(NSInteger)y{

    if (y <0) {

        return @"错误日期格式!!!";

    }

    

    NSString *zodiacString = @"鼠牛虎兔龙蛇马羊猴鸡狗猪";

    

    NSRange range = NSMakeRange ((y+9)%12-1, 1);

    

    NSString*  result = [zodiacString  substringWithRange:range];

    

    return [result stringByAppendingString:@""];

    

}

写了一个demo,需要的去这里下载:https://github.com/wangdachui/WTZodiacSigns

你可能感兴趣的:(ios)