-1

I have string with value 01012016 which i want to show to user like 01-01-2016. For this, i am using the below code

-(NSString *)dateToFormatedDate:(NSString *)dateStr {

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

    [dateFormatter setDateFormat:@"MM-dd-yyyy"];
    NSDate *date = [dateFormatter dateFromString:dateStr];

    NSLog(@"date is %@", [dateFormatter stringFromDate:date]);
    return [dateFormatter stringFromDate:date];
}

But this method is always returning nil. I have tried on simulator and device both. I am not able to figure it out what i did wrong here

YvesLeBorg
  • 9,070
  • 8
  • 35
  • 48
Nitya
  • 449
  • 1
  • 8
  • 24
  • 3
    Have you tried `[dateFormatter setDateFormat:@"MMddyyyy"];` when reading the string and then `[dateFormatter setDateFormat:@"MM-dd-yyyy"];` when writing it? – Putz1103 Mar 07 '16 at 20:49
  • Check out http://nsdateformatter.com for examples of date formats. – Alex Rouse Mar 07 '16 at 21:03

1 Answers1

2

The format of your NSDateFormatter does not match the string you're trying to pass it. Take a look at this related question...

Converting a string to an NSDate

What you want to do is set the NSDateFormatter to match the string, then once you've created an NSDate object from the string, change the NSDateFormatter to your desired output format. Something like this...

-(NSString *)dateToFormatedDate:(NSString *)dateStr {

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

  [dateFormatter setDateFormat:@"MMddyyyy"];
  NSDate *date = [dateFormatter dateFromString:dateStr];
  [dateFormatter setDateFormat:@"MM-dd-yyyy"];

  NSLog(@"date is %@", [dateFormatter stringFromDate:date]);
  return [dateFormatter stringFromDate:date];
}
Community
  • 1
  • 1
Nick Fox
  • 578
  • 3
  • 8