0

I have this piece of code:

 // Convert string to date object
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"MMMM d, YYYY"];
        NSDate *formatDate = [dateFormat dateFromString:self.date];
        NSLog(@"1-%@", self.date);
        NSLog(@"2-%@", formatDate);
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:formatDate];
        NSString *dateCal = [NSString stringWithFormat:@"%d/%d/%d", [components day], [components month], [components year]];
        NSLog(@"3-%@", dateCal);
        milage.date = dateCal;

The first NSLog returns:

1-March 23, 2012

The second:

2-2011-12-25 00:00:00 +0000

The third:

3-25/12/2011

Why does the date change when getting the date from the string and formatting it? I'm expecting the third NSLog (or dateCal) to equal 23/3/2012. I live in the UK so its not to do with the timezone..

Thanks,

Jack

Jack Nutkins
  • 1,555
  • 5
  • 36
  • 71
  • 1
    I'm surprised that you see "March 23, 2012" when you NSLog self.date. On my machine, NSLog(@"%@", [NSDate date]); yields a date like "2012-03-23 14:47:48 +0000". – danh Mar 23 '12 at 14:50
  • 2
    Thanks, just needed to use 'yyyy' instead.. – Jack Nutkins Mar 23 '12 at 14:51
  • Here's a test, see whether this condition holds [self.date timeIntervalSinceReferenceDate] == [formatDate timeIntervalSinceReferenceDate]. (Ugly formatting, sorry, but since this isn't really an answer, I figured it should be a comment). – danh Mar 23 '12 at 14:52
  • 1
    @danh `self.date` is a string. – Joe Mar 23 '12 at 14:52
  • its a string, but why does my code work when I use the lower case 'yyyy' as opposed to 'YYYY'? – Jack Nutkins Mar 23 '12 at 14:55
  • Oh. sorry for the dim-witted-ness. It looks like uppercase Y's mean week of the year. (http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns) – danh Mar 23 '12 at 15:05

3 Answers3

3

Needed to use lower case 'y' in the line:

[dateFormat setDateFormat:@"MMMM d, YYYY"];
Jack Nutkins
  • 1,555
  • 5
  • 36
  • 71
2

Have you used the setLocale method?

Also, from the technical Q&A:

If you're working with user-visible dates, you should avoid setting a date format string because it's very hard to predict how your format string will be expressed in all possible user configurations. Rather, you should try and limit yourself to setting date and time styles (via -[NSDateFormatter setDateStyle:] and -[NSDateFormatter setTimeStyle:]).

Brooks Hanes
  • 425
  • 2
  • 12
0

Use [dateFormat setDateStyle:NSDateFormatterLongStyle];
Instead of [dateFormat setDateFormat:@"MMMM d, YYYY"];
Will give you reason as soon as I find it.

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184