0

I have a NSString like this 05/09/2015 then I want to convert it into this format 2014-07-28 18:30:00 +0000

that second date was the one that I get from the system date. That date can be placed nicely on Tapku calender. but my string is the first one. I want to convert that 1st date just like as the date format that im getting from the system date. How can I do that.

Please help me. Thanks

Wyetro
  • 8,439
  • 9
  • 46
  • 64
user2889249
  • 899
  • 2
  • 13
  • 22

1 Answers1

1

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

NSDateFormatter *otherFormatter = [[NSDateFormatter alloc] init];
[otherFormatter setDateFormat:@"yyyy-MM-dd"];
//[otherFormatter setTimeStyle:NSDateFormatterMediumStyle];

NSString *resultString = [otherFormatter stringFromDate:dateFromString];
NSLog(@"%@", resultString);

And then you can convert it back to an NSDate or keep as an NSString.

See this: Click Here

Community
  • 1
  • 1
Wyetro
  • 8,439
  • 9
  • 46
  • 64
  • but how can I get the Time. 2014-07-28 18:30:00 +0000 this is the format I need, currently I have just a string like dd/mm/yyy – user2889249 Jul 29 '14 at 04:05
  • There is an issue with displaying the time. Since the original date does not have time you can not format the time (as seen in my answer with the time formatter commented out). This answer will turn a string in the format of dd-MM-yyyy into a string with yyyy-MM-dd. – Wyetro Jul 29 '14 at 04:23
  • But here when I give dateFromString = [dateFormatter dateFromString:dateString]; this dateFromString become nil why is that? – user2889249 Jul 29 '14 at 04:31
  • What is the format of your original string? Is it not dd-MM-yyyy? – Wyetro Jul 29 '14 at 04:34
  • 1
    Read the comment in the code, if the format doesn't match up it will become nil. – Wyetro Jul 29 '14 at 04:34