由NSDate轉換為NSString:
SDateFormatter*dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString*strDate = [dateFormatter stringFromDate:[NSDate date]];
由NSString轉換為NSDate:
NSDateFormatter*dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date =[dateFormatter dateFromString:@"2010-08-04 16:01:03"];
比較2個時間段的間隔
NSCalendar *cal = [NSCalendar currentCalendar];
unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [cal components:unitFlags fromDate:[self.formatter dateFromString:sendString] toDate:[self.formatter dateFromString:endSreing] options:0];
日期之間比較可用以下方法
-(BOOL)isEqualToDate:(NSDate *)otherDate;
與otherDate比較,相同返回YES
- (NSDate*)earlierDate:(NSDate *)anotherDate;
與anotherDate比較,返回較早的那個日期
- (NSDate*)laterDate:(NSDate *)anotherDate;
與anotherDate比較,返回較晚的那個日期
-(NSComparisonResult)compare:(NSDate *)other;
該方法用于排序時調用:
.當實例保存的日期值與anotherDate相同時返回NSOrderedSame
.當實例保存的日期值晚于anotherDate時返回NSOrderedDescending
.當實例保存的日期值早于anotherDate時返回NSOrderedAscending