iOS 获取周几

根据传入的日期,得到是周几,传入的格式是NSDate,直接上代码:

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {

    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

    [calendar setTimeZone: timeZone];

    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;

    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];

    return [weekdays objectAtIndex:theComponents.weekday];

}

默认周日为1,以此类推.

1、 创建或初始化可用以下方法

`+ (id)currentCalendar;`    取得当前用户的逻辑日历(logical calendar)

`+ (id)autoupdatingCurrentCalendar;` 取得当前用户的逻辑日历(logical calendar), ......
- (id)initWithCalendarIdentifier:(NSString *)identifier;

初始化为各种日历。identifier的范围可以是:

NSCalendarIdentifierGregorian   阳历
NSCalendarIdentifierBuddhist    佛历
NSCalendarIdentifierChinese     中国日历        
NSCalendarIdentifierCoptic      埃及日历        
NSCalendarIdentifierEthiopicAmeteMihret 埃塞俄比亚
NSCalendarIdentifierEthiopicAmeteAlem   
NSCalendarIdentifierHebrew       希伯来日历        NSCalendarIdentifierISO8601    ISO8601(但是现在还不可用)         
NSCalendarIdentifierIndian      印度日历    
NSCalendarIdentifierIslamic     伊斯兰教日历        
NSCalendarIdentifierIslamicCivil  伊斯兰教民事日历       NSCalendarIdentifierJapanese       日本日历     
NSCalendarIdentifierPersian      波斯        NSCalendarIdentifierRepublicOfChina  中华民国日历(台湾) 
NSCalendarIdentifierIslamicTabular    NSCalendarIdentifierIslamicUmmAlQura   

2、使用前若有必要可以先做以下设定
- (void)setLocale:(NSLocale *)locale; 设置区域
- (void)setTimeZone:(NSTimeZone *)tz; 设置时区

- (void)setFirstWeekday:(NSUInteger)value;
  • 设定每周的第一天从星期几开始,比如:

    . 如需设定从星期日开始,则value传入1

    . 如需设定从星期一开始,则value传入2

    . 以此类推

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章