Fork me on GitHub

Programming Design Notes

Objective-C - NSString 和 NSDate 互相轉換

| Comments

記錄一下在 Objective-CNSString 轉換為 NSDateNSDate 轉換為 NSString 的方法。

很簡單,使用 NSDateFormatter 就可以令 NSStringNSDate 互相轉換。

NSDate 轉換為 NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);
[dateFormatter release];

結果:
2010-08-04 16: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);
[dateFormatter release];

結果:
2010-08-04 16:01:03 +0800

從 Objective-C 轉到 Swift 可看看這篇: From Objective-C to Learning Swift


相關書籍: Programming in Objective-C 2.0 (2nd Edition)Learn Objective–C on the Mac (Learn Series)Programming in Objective-C