码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2014-12-16 22:26:14      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   sp   for   

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

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

- (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 根据生日得到生肖,星座,年龄的算法

标签:style   blog   http   ar   io   color   os   sp   for   

原文地址:http://www.cnblogs.com/6duxz/p/4168190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!