2012-11-20 53 views
2

可能重複:
How do I get the day of the week in Objective-C?沒有能夠得到一週的一天,顯示

我有一個連接到的NSString一個UILabel。但是,我試圖將nsstring設置爲星期幾(星期一,星期二等)。每次我運行它,它都不會給我任何東西。我有一種感覺,那是因爲我沒有從我的nsdate獲得價值。但是,我是xcode的新手,所以我不知道我做錯了什麼。

-(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; 
} 

回答

1

試試這個代碼,而不是:

-(void)viewDidLoad { 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ; 
    [formatter setDateFormat:@"EEEE"]; 
    _label.text = [formatter stringFromDate:[NSDate date]]; 
} 
+0

哇!謝謝!!!! – user1803649

0

的主要問題是,你正嘗試在NSDateComponents對象分配給NSString變量。

由@JShapiro給出的答案是一個很好的答案。但如果你想使用NSDateComponents你可以這樣做:

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];