2013-10-10 54 views
0

即時更改基於星期幾的文本值,我能夠使用字符串值來實現此目的,但是我希望能夠實現一個數字值 - 而不是刪除問題不同的語言。例如,如果今天是星期一,但是如果今天是第一天,那麼我想要。我試過下面的代碼,但它給了我一個數值0;數字值:星期幾

NSDateFormatter *dayofweekformatter = [[NSDateFormatter alloc] init]; 
[dayofweekformatter setDateFormat:@"E"]; 

NSString *DayOfWeek = [dayofweekformatter stringFromDate:[NSDate date]]; 
NSInteger weekDay = [DayOfWeek integerValue]; 
NSLog(@"The day of the week is: %d", weekDay); 

可以做到這一點嗎?

回答

0

this鏈接,「E」對自己會給你一週中的一天,一個文本格式,即:如果你想的這一天「星期一」 /「星期二」等

周作爲一個整數,你應該使用小寫「e」或「c」。

另一種實現方式是使用NSCalendarNSDateComponents來確定星期幾,因爲這更可能考慮到基於用戶首選日曆的不同設備之間的不同設置。

NSDate *date = [NSDate date]; 

NSCalendar *calendar = [NSCalendar currentCalendar]; 

NSDateComponents *dateComponents = [calendar components:NSCalendarUnitWeekday fromDate:date]; 

NSLog(@"day of the week: %i", [dateComponents weekday]); 
+0

非常感謝,工作就像一個魅力。你能否詳細說明「不同的實現......」 – DevC

+0

當然。我用一些示例代碼更新了我的答案。 – CaptainRedmuff

+0

再次感謝隊長 – DevC

0

這裏建議在蘋果論壇https://discussions.apple.com/thread/1700102?start=0&tstart=0解決方案(我不是作者)

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest]; 

NSInteger weekday = [weekdayComponents weekday]; 
// weekday 1 = Sunday for Gregorian calendar 

[gregorian release]; 
+0

謝謝,'dateOfInterest'是什麼? – DevC