结合NSCalendar和NSDate能做更多的日期\时间处理 获得NSCalendar对象
NSCalendar *calendar = [NSCalendar currentCalendar];?获得年月日
- (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)date;
//创建日期
NSDate?*d = [NSDate?date];
//创建日期对象
NSCalendar?*ca = [NSCalendar?currentCalendar];
//获得时间组件
NSDateComponents?*cms= [ca?components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:d];
NSLog(@"%ld-%ld-%ld",cms.year,cms.month,cms.day);
比较两个日期的差距
- (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *) startingDate toDate:(NSDate *)resultDate options:(NSCalendarOptions)opts;
NSString *time1 [email protected]"2014-04-08 20:50:40"; NSString *time2 [email protected]"2014-04-04 18:45:30";
NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat [email protected]"yyyy-MM-dd HH:mm:ss";
NSDate *date1 = [fmt dateFromString:time1]; NSDate *date2 = [fmt dateFromString:time2];
?//取时间较早的那个
? ?? [date2?earlierDate:date1];
? ? ? ?
?//取较晚的那个
? ?? [date2?laterDate:date1];
//把字符串转换成日期
? ? ? ? //和上边类似,仍然需要日期格式化对象,但是调用的方法从stringFromDate变成
? ? ? ? //因为时区设置的问题,这个日期被减去了一天
? ? ? ? NSDateFormatter?*format2=[[NSDateFormatter?alloc]init];
? ? ? ? [format2?setDateFormat:@"yyyy/MM/dd"];
? ? ? ? NSString?*[email protected]"2014/10/11";
? ? ? ? NSLog(@"%@",[format2?dateFromString:str2]);
// 1.创建一个日历对象
NSCalendar?*calendar = [NSCalendar?currentCalendar];
// 2.比较时间的差距
int?unit =?NSCalendarUnitYear?|?NSCalendarUnitMonth?|?NSCalendarUnitDay
|?NSCalendarUnitHour?|?NSCalendarUnitMinute?|?NSCalendarUnitSecond;?
NSDateComponents?*cmps = [calendar?components:unit?fromDate:date2?toDate:date1?options:0];
NSLog(@"相差%ld年%ld月%ld天%ld小时%ld分钟%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);
计算日期
//1)明天的此刻
NSTimeInterval secondsPerDay = 24*60*60;
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay]; NSLog(@"myDate = %@",tomorrow);
//2)昨天的现在
NSTimeInterval secondsPerDay1 = 24*60*60;
NSDate *now = [NSDate date];
NSDate *yesterDay = [now addTimeInterval:-secondsPerDay1]; NSLog(@"yesterDay = %@",yesterDay);
格式化日期
NSDate ----> dateString
//定义NSDate
NSDate?*d1 = [NSDate?date];
//定义日期时间格式化的类
NSDateFormatter?*formatter = [[NSDateFormatter?alloc]?init]; [email protected]"yyyy-MM-dd HH:mm:ss";
//把Date转换为dataStr
NSString?*dateStr = [formatter?stringFromDate:d1];
- //??设置格式
- //??fmt.dateFormat = @"今天?HH:mm";
- //??HH : 24小时制
- //??hh : 12小时制
- //??yyyy :?年
- //??MM :?月
- //??dd :?号
- //??mm :?分钟
- //??ss :?秒
- //??Z :?时区