-3

I'm pretty new to objective-c and I have a date stored in a sqlite table as an integer e.g. 20131017 (which represents Oct 17, 2013). I want to display this to the user in the format Oct 17, 2013 but my code produces a null when I log it.

No doubt something very fundamental I'm missing - but for the life of me I can't see it.

Here's the code:

_fromDate.text = _startDate; //e.g.20131017 (representing Oct 17, 2013)

NSString *dateString =[NSString stringWithFormat:@"%d", [_fromDate.text intValue]];
NSLog(@"dateString: %@", dateString);// shows 20131017 ok

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMM dd, yyyy"];
NSDate *date = [dateFormat dateFromString:dateString];
NSLog(@"date: %@", date);  //produces a nil result

Appreciate any help. Thx.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
ianM
  • 393
  • 1
  • 3
  • 16
  • 1
    That's not how a date formatter works. Read the documentation better. This has already been discussed multiple times here. –  Oct 17 '13 at 21:00
  • Uh, if you're going to use a date formatter to parse a character date, the "date format" should more or less resemble the string you're trying to parse. – Hot Licks Oct 17 '13 at 21:18
  • possible duplicate of [How to parse a date string into an NSDate object in iOS?](http://stackoverflow.com/questions/4999396/how-to-parse-a-date-string-into-an-nsdate-object-in-ios) – Ben Flynn Oct 17 '13 at 21:38
  • 1
    Why do you take a string (`_fromDate.text`), convert it to an `int`, then use a string format to convert the `int` back into the same string? Just do `NSString *dateString = _fromDate.text;`. And as been covered here by countless existing questions, to convert from one format to another you need two different date formats to do the conversion. – rmaddy Oct 17 '13 at 21:43

1 Answers1

2

With this bit of code:

[dateFormat setDateFormat:@"MMM dd, yyyy"];
NSDate *date = [dateFormat dateFromString:dateString];

you're saying:

  1. This is my date format
  2. Convert this string, which is in the format I just told you about, into a date

But the string isn't in that format, so it doesn't work.

The format is actually: @"yyyyMMdd" (or something like that, I don't have the spec to hand).

You really need 2 formats (and 2 formatters)...

  1. The format to convert your stored string to a date
  2. The format to convert your date into your display string (this is the one you already had)
Wain
  • 118,658
  • 15
  • 128
  • 151