主方法:
+ (NSString *)weekdayStringFromDate:(NSDate *)inputDate
{
//知道為什么加一個null類型嗎?
//因?yàn)閿?shù)組的下標(biāo)是以0開始的
//而星期的對應(yīng)數(shù)字范圍是1-7
//所以加一個null類型(不會取到這個null值)
NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
[calendar setTimeZone: timeZone];
NSDateComponents *theComponents = [calendar components:NSCalendarUnitWeekday fromDate:inputDate];
return [weekdays objectAtIndex:theComponents.weekday];
}
顯示當(dāng)天的星期:
/**
* 返回當(dāng)天星期
*/
+ (NSString *)currentWeekday
{
return [self weekdayStringFromDate:[NSDate date]];
}
顯示具體時間的星期:
/**
* 根據(jù)具體時間顯示星期
*
* @param timeStr 目標(biāo)時間
* @return 返回星期
*/
+ (NSString *)weekdayStringWithTime:(NSString *)timeStr
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[formatter setTimeZone:timeZone];
NSDate *date = [formatter dateFromString:timeStr];
return [self weekdayStringFromDate:date];
}
有需要顯示星期需求的,建議寫在NSString
的分類里诚亚,這樣比較方便更新與查看脏毯。