SPUDERMAN
SPUDERMAN

Reputation: 187

Why is Sunday always -1?

Below is the code:

-(int)getSystemDay
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger day = [components weekday];
    int weekday = (int) day;
    return weekday;
}

As I know, int for Sunday is always 1 but in my case when I print out weekday, it gives -1. Why is it so ?

Upvotes: 0

Views: 67

Answers (1)

vadian
vadian

Reputation: 285082

You don't specify the NSCalendarUnitWeekday component, so the value is not retrieved.
An unspecified date component is -1 in Objective-C.

If you need only one component there is a more convenient way:

-(NSInteger)getSystemDay
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    return [gregorian component:NSCalendarUnitWeekday fromDate:[NSDate date]];
}

Upvotes: 2

Related Questions