在開發行事曆、提醒或任何需要顯示星期資訊的功能時,取得「今天是星期幾」是很常見的需求。做法是利用 NSDateFormatter 並將日期格式設為特定的格式符號即可。以下程式碼示範如何取得目前所在的星期:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog(@"現在所在的周:%@",[self getWeekFromLocal]); } //活的現在的周的日期,格式:Wednesday -(NSString*)getWeekFromLocal{ NSDate * senddate=[NSDate date]; NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init]; [dateformatter setDateFormat:@"EEEE"]; NSString * locationString=[dateformatter stringFromDate:senddate]; NSLog(@"locationString:%@",locationString); return locationString; } 輸出:
2015-03-11 15:50:31.628 獲得現在的周[5165:203827] locationString:Wednesday
2015-03-11 15:50:31.648 獲得現在的周[5165:203827] 現在所在的周:Wednesday
關鍵在於 setDateFormat:@"EEEE"——其中 EEEE 代表完整的星期名稱(如 Wednesday)。若想輸出中文星期或不同格式,只要調整格式字串即可,例如改用其他格式符號搭配 locale 設定,就能得到本地化的星期表示法。