Claus
Claus

Reputation: 5722

Wrong year set when converting NSDate to NSString

I'm trying to produce a string using a NSDate category in this way:

NSString* dateString = nil;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocal currentLocale]];
[dateFormat setDateFormat:@"dd LLL YYYY"];
dateString = [dateFormat stringFromDate:self];
return dateString;

The conversion works fine except in ONE case (I report the debug session): if I try to convert an NSDate object like this:

(gdb) po self
2012-01-01 00:00:00 +0000

I obtain:

(gdb) po dateString
01 Jan 2011

Why the year is set back to 2011????

PS. I have already checked NSDate returns wrong year and I'm NOT using the Japanese calendar.

thanks a lot

Upvotes: 2

Views: 535

Answers (1)

Daniele Pratelli
Daniele Pratelli

Reputation: 34

Try this:

     NSDate *pickerDate = [NSDate date];
     NSCalendar*       calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
     NSDateComponents* components = [[[NSDateComponents alloc] init] autorelease];
        components.day = 0; //This value to take from today to next 1 or 2 or 3 days
        NSDate* newDate = [calendar dateByAddingComponents: components toDate: pickerDate options: 0];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MMMM"];
        NSString *textDate = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:newDate]];
        [dateFormatter release];

Upvotes: 2

Related Questions