For my iPhone app I got to convert NSDate object to string, and then convert the string back to NSDate object.. Can someone help me out? thank you!
Asked
Active
Viewed 335 times
0
-
Instead of converting the NSDate into a string and then back into an NSDate, you will probably want to keep the NSDate as it is and create an additional NSString object to represent it. – Mark Leonard May 16 '11 at 13:43
3 Answers
2
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];

Jhaliya - Praveen Sharma
- 31,697
- 9
- 72
- 76
1
You need to check out NSDateFormatter
this does exactly this, both directions.

MarkPowell
- 16,482
- 7
- 61
- 77
0
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];

Tom Irving
- 10,041
- 6
- 47
- 63

Deepesh
- 633
- 4
- 11