views:

111

answers:

3

I need to be able to get the weekday from nsdate, i have the following code and it always return 1. I tried to change the month, i tried everything from 1 to 12 but the result of the week day is always 1.

NSDate *date2 = [[NSDate alloc] initWithString:[NSString stringWithFormat:@"%d-%d-%d", 2010, 6, 1]];
unsigned units2 = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSCalendar *calendar2 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components2 = [calendar2 components:units2 fromDate:date2];
int startWeekDay = [components2 weekday];
[date2 release];
[calendar2 release];
+4  A: 

Edit for Mac:

The format of the string has to be —YYYY-MM-DD HH:MM:SS ±HHMM according to the docs, all fields mandatory

Old answer (for iPhone and tested on simulator):

There is no (public) -initWithString: method in NSDate, and what you get returned is not what you expect.

Use a properly configured (you need to give the input format) NSDateFormatter and -dateFromString:.

Eiko
yes there is > – initWithString: and my problem was the format of my string
aryaxt
Ah sorry, looked in the iPhone NSDate which lacks this. I edit my answer...
Eiko
+2  A: 

Creating an NSDateFormatter that only contains the weekday will do what you want.

NSDate *now = [NSDate date];
NSDateFormatter *weekday = [[[NSDateFormatter alloc] init] autorelease];
[weekday setDateFormat: @"EEEE"];
NSLog(@"The day of the week is: %@", [weekday stringFromDate:now]);

If you need internationalization, the NSDateFormatter can be sent a locale, which will give the proper translation.

The date formatters are controlled through this standard: Unicode Date Formats

jshier
I think the OP wants an integer of the day of the week (for example, 1 = Monday, 2 = Tuesday, 3 = Wednesday, etc).
dreamlax
yes, that's what i was looking for
aryaxt
A: 

I solved the problem, The problem was that the format of my date string was wrong:

NSDate *date = [[NSDate alloc] initWithString:[NSString stringWithFormat:@"%d-%d-%d 10:45:32 +0600", selectedYear, selectedMonth, selectedDay]];

and since i don't care about the time i randomly pass a time to the end of the string

aryaxt