3

Possible Duplicate:
how to convert datetime format in NSString?

I have stored date in string from json parsing. The format of date is 2011-1-24. Now i want to convert into MM-dd-YYYY format. For that i am using this code

NSString *stringDate =[NSString stringWithFormat:@"%@",[list_date objectAtIndex:indexPath.row]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy"];
NSDate *date  = [dateFormatter dateFromString:stringDate];
NSString *newDate = [dateFormatter stringFromDate:date];

But it show null value. What is problem in this code?

Thanks in advance...

Community
  • 1
  • 1
iRam11
  • 309
  • 4
  • 16

2 Answers2

12

It is different from @Mayur Joshi's answer though it looks to be same.

This is sure to work for you.

 NSString *dateString = @"2011-09-19";
 NSDateFormatter *format = [[NSDateFormatter alloc] init];
 [format setDateFormat:@"yyyy-MM-dd"];
 NSDate *date = [format dateFromString:dateString];
 [format setDateFormat:@"MM-dd-yyyy"];
 NSString* finalDateString = [format stringFromDate:date];
 [format release];

I hope this helps you.

If you need any help on this then please leave a comment below.

Also you can refer to this link for more help. This link is really similar to what you want, only the target date Format is different.

How to convert date string into format "17 Nov 2010"

Community
  • 1
  • 1
Parth Bhatt
  • 19,381
  • 28
  • 133
  • 216
  • 1
    @Mayur: 'YYYY' is replaced with small 'yyyy' which stands for the Year.All I can say is that 'YYYY' does not work. Also duplicate declaration of NSString is removed. It is the basic concept which was wrongly displayed though your intention may not be wrong. :) – Parth Bhatt Sep 19 '11 at 05:55
0
 NSString *dateStr = @"2011-1-24";

 //OR if you have date then declare dateStr like this, 
 NSString *dateStr = [NSString stringWithFormat:@"%@",yourDate];

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"YYYY-M-dd"];
 NSDate *date = [dateFormat dateFromString:dateStr];
 [dateFormat setDateFormat:@"MM-dd-YYYY"];
 NSString* temp = [dateFormat stringFromDate:date];
 [dateFormat release];

 NSLog(@"%@",temp);
mayuur
  • 4,736
  • 4
  • 30
  • 65