开发者

NSDate and NSString cocoa

开发者 https://www.devze.com 2023-03-06 10:37 出处:网络
For my iPhone app I got to开发者_StackOverflow convert NSDate object to string, and then convert the string back to NSDate object.. Can someone help me out? thank you!Use to convert from NSDate to NSS

For my iPhone app I got to开发者_StackOverflow convert NSDate object to string, and then convert the string back to NSDate object.. Can someone help me out? thank you!


Use to convert from NSDate to NSString

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

Use to convert from NSString to NSDate.

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


You need to check out NSDateFormatter this does exactly this, both directions.


convert NSDate to NSString

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

//Optionally for time zone converstions

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

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];

Convert NSString to 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];
0

精彩评论

暂无评论...
验证码 换一张
取 消