iOS 日期(NSDate)的常用操作总结

1.获取当前年月日

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd"]; //日期格式

    //如果还想要获取时分秒,直接在这里指定时分秒的OPTIONS就行了.
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday; 

    NSDateComponents *component = [calendar components:unit fromDate:[NSDate date]];
    //获取年月日操作,时分秒也是这个api,只是调用属性不同而已.记得unit要加上时分秒的OPTIONS哦
    NSInteger currentYear = component.year;
    NSInteger currentMonth = component.month;
    NSInteger currentDay = component.day;

2.获取或者月份的天数

2.1获取当前或者当前有多少天

NSCalendar *calendar = [NSCalendar currentCalendar];

//把NSCalendarUnitMonth换成NSCalendarUnitYear就能获取当前年有多少天
NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
NSLog(@"%zi",range.length);

2.2 获取指定月份有多少天

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM"];
    NSDate *date = [formatter dateFromString:@"2016/1"];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];//只需要把date设置成指定日期,就能获取到指定月份的天数了
NSLog(@"%zi",range.length);
posted @ 2015-12-04 17:22  张孝平  阅读(550)  评论(0编辑  收藏  举报