主方法:
+ (NSString *)weekdayStringFromDate:(NSDate *)inputDate
{
//知道为什么加一个null类型吗?
//因为数组的下标是以0开始的
//而星期的对应数字范围是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];
}
显示当天的星期:
/**
* 返回当天星期
*/
+ (NSString *)currentWeekday
{
return [self weekdayStringFromDate:[NSDate date]];
}
显示具体时间的星期:
/**
* 根据具体时间显示星期
*
* @param timeStr 目标时间
* @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
的分类里,这样比较方便更新与查看。