2011-05-16 89 views
0

對於我的iPhone應用程序,我得將NSDate對象轉換爲字符串,然後將字符串轉換回NSDate對象。有人可以幫我嗎?謝謝!NSDate和NSString可可

+0

相反轉換的NSDate成一個字符串,然後回一個NSDate,你大概會想要保持NSDate的原樣並創建一個額外的NSString對象來表示它。 – 2011-05-16 13:43:48

回答

2

使用轉換從NSDateNSString

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss a"]; 
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance]; 

使用轉換從NSStringNSDate

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss a"]; 
NSDate *myDate = [df dateFromString: stringFromDate]; 
1

你需要檢查NSDateFormatter這正是這兩個方向。

0

轉換的NSDate到的NSString

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"yyyy"]; 

//Optionally for time zone converstions 

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; 

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance]; 

轉換的NSString的NSDate

NSString *dateString = @"01-02-2010"; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

// this is imporant - we set our input date format to match our input string 
// if format doesn't match you'll get nil from your string, so be careful 

[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 

NSDate *dateFromString = [[NSDate alloc] init]; 

// voila! 
dateFromString = [dateFormatter dateFromString:dateString]; 

[dateFormatter release];