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

6
  • 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". Commented Mar 23, 2012 at 14:50
  • 2
    Thanks, just needed to use 'yyyy' instead.. Commented Mar 23, 2012 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). Commented Mar 23, 2012 at 14:52
  • 1
    @danh self.date is a string. Commented Mar 23, 2012 at 14:52
  • its a string, but why does my code work when I use the lower case 'yyyy' as opposed to 'YYYY'? Commented Mar 23, 2012 at 14:55

3 Answers 3

3

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

[dateFormat setDateFormat:@"MMMM d, YYYY"]; 
Sign up to request clarification or add additional context in comments.

2 Comments

Why does the uppercase YYYY results in a wrong year?
YYYY gives the week of the year, '1 Jan 2022' belongs to last week of 2021 so 'YYYY' return 2021 as year.
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:]).

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.