How would I convert an NSString like "01/02/10" (meaning 1st February 2010) into an NSDate? And how could I turn the NSDate back into a string?
+2
A:
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];
NSDate convert to NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);
[dateFormatter release];
PK
Pavan
2010-10-12 17:19:48
should that be two ys in the setDateFormat?
cannyboy
2010-10-12 17:34:33
im not sure if 2 y's work. but rule of thumb is what ever format youre going to gave keeo the same format for the setDateFormat. so first trty 2010 and write 4 y's like so 'yyyy'. as im sure that will defnitely work
Pavan
2010-10-12 17:48:31
+1
A:
using "10" for representing a year is not good, because it can be 1910, 1810, etc. You probably should use 4 digits for that.
If you can change the date to something like
yyyymmdd
than you can use:
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
Digital Robot
2010-10-12 17:20:19