2

Possible Duplicate:
How do I get the day of the week in Objective-C?

I have a uilabel that is connected to a nsstring. However, I am trying to set the nsstring to the day of the week (monday, tuesday, etc.). Every time I run it though, it gives me nothing. I have a feeling though that it is because I am not getting a value from my nsdate. However, I'm new to xcode, so I don't really know understand what I've done wrong.

-(void)viewDidLoad {
     NSDate *today = [[NSDate alloc] init];
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSGregorianCalendar];

        // Get the weekday component of the current date
        NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
                                                           fromDate:today];

       NSString *dateString = weekdayComponents;
        _label.text = dateString;
}
Community
  • 1
  • 1
user1803649
  • 263
  • 1
  • 3
  • 11

2 Answers2

1

Try this code instead:

-(void)viewDidLoad {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"EEEE"];
    _label.text = [formatter stringFromDate:[NSDate date]];
}
J Shapiro
  • 3,861
  • 1
  • 19
  • 29
0

A primary issue is that you are attempting to assign an NSDateComponents object to an NSString variable.

The answer given by @JShapiro is a good one. But if you want to use NSDateComponents you could do this:

NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
NSInteger weekday = [weekdayComponents weekday];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSArray *weekdayNames = [formatter weekdaySymbols];

_label.text = weekdayNames[weekday];
rmaddy
  • 314,917
  • 42
  • 532
  • 579