標籤:
由 NSDate 轉換為 NSString:
- NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
- [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
- NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
- NSLog(@"%@", strDate);
結果:
- 2015-06-14 13:01:03
由 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"];
- NSLog(@"%@", date);
結果:
- 2015-06-14 13:01:03 +0800
日期之間比較可用以下方法
- (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
IOS NSString與NSDate互相轉換及NSDate比較