1

Possible Duplicate:
Convert NSDate to NSString
convert string to nsdate

Currently I have this code. It's for adding events to the calendar.

[...]
event.startDate = [[NSDate date] dateByAddingTimeInterval:86400];
event.endDate = [[NSDate date] dateByAddingTimeInterval:90000];

What I need is the code to add to a spesific start date and end date, and that's where NSString comes in handy. But I've had no luck converting it so far.

Community
  • 1
  • 1
GThaman Titan
  • 41
  • 1
  • 4

3 Answers3

5

Refer this code :

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];

Hope it helps you

P.J
  • 6,547
  • 9
  • 44
  • 74
0

convert NSDate to NSString as

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

NSString *string = [dateFormatter stringFromDate:date];
[dateFormatter release];
ask4asif
  • 676
  • 4
  • 10
0

That's an example if you need the format like “Nov 23, 1937”:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle= NSDateFormatterMediumStyle;
NSString* string= [formatter stringFromDate: date];

Check out the reference for other styles. If you need another style that hasn't a constant, you can use the date format, in this case it's:

formatter.dateFormat= @"MMM dd, yyyy"; // same as medium style

But the preferred way is to use the style, use the format only if there isn't a propert style.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187