一.获取当前时间
1.1创建一个日期对象
NSDate *date = [NSDate date];NSLog(@"%@",date);
输出结果:
2016-07-01 17:31:02.410 OCString[907:402963] 2016-07-01 09:31:02 +0000 //因为时区不一样,需要格式化为本地时间
Program ended with exit code: 0
1.2将时间格式化为本地时间
//日前格式化NSDateFormatter *formatter = [[NSDateFormatter alloc]init];//设置日期格式化对象的两个属性formatter.dateStyle = NSDateFormatterShortStyle;formatter.timeStyle = NSDateFormatterShortStyle;NSString *result = [formatter stringFromDate:date];NSLog(@"%@",result);
输出结果:
2016-07-01 17:36:20.719 OCString[917:424185] 16/7/1 17:36
Program ended with exit code: 0
二.获取当月一共有多少天
2.1创建一个日期对象
NSDate *date = [NSDate date];
2.2获取系统提供的日历对象
//获取系统提供的日历对象NSCalendar *calender = [NSCalendar currentCalendar];
2.3获取当月第一天和最后一天
NSRange range = [calender rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];NSLog(@"%@",NSStringFromRange(range));
输出结果:
2016-07-01 17:46:21.526 OCString[947:466115] {1, 31}
Program ended with exit code: 0
三.获取当年一共有多少天
同上二中的方法
四.获取当月第一天和最后一天是星期几
4.1获取当月第一天是星期几
NSDate *date = [NSDate date];
4.2获取系统提供的日历对象
NSCalendar *calender = [NSCalendar currentCalendar];
4.3获取当月第一天和最后一天
NSRange range = [calender rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
4.4获取当天时间的日期值
NSDateComponents *todayComp = [calender components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
4.5计算第一天的日期
NSDateComponents *startComp = [todayComp copy];startComp.day = range.location;
4.6计算最后一天的日期
NSDateComponents *endComp = [todayComp copy];endComp.day = range.length;
4.7日期转为时间对象
NSDate *startDate = [calender dateFromComponents:startComp];NSDate *endDate = [calender dateFromComponents:endComp];
4.8计算星期几
NSInteger start_week = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfYear forDate:startDate];NSInteger end_week = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfYear forDate:endDate];