标签:
结合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 =?@"2014-04-08 20:50:40"; NSString *time2 =?@"2014-04-04 18:45:30";
NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat =?@"yyyy-MM-dd HH:mm:ss";
// 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];
//2)昨天的现在
NSTimeInterval secondsPerDay1 = 24*60*60;
格式化日期
NSDate ----> dateString
//定义NSDate
NSDate?*d1 = [NSDate?date];
//定义日期时间格式化的类
NSDateFormatter?*formatter = [[NSDateFormatter?alloc]?init]; formatter.dateFormat?=?@"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 :?秒
标签:
原文地址:http://www.cnblogs.com/deng1989/p/4595265.html