Vla*_*mir 216

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];  
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);
Run Code Online (Sandbox Code Playgroud)

输出当前星期几作为区域设置中的字符串,具体取决于当前的区域设置.

要获得一个星期的数字,您必须使用NSCalendar类:

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];
Run Code Online (Sandbox Code Playgroud)

  • 要获得所有工作日的名称,您可以使用`[dateFormatter weekdaySymbols]`(和类似的),它返回NSStrings的NSArray,从星期日开始,索引为0. (14认同)
  • @VovaStajilov可能是这个问题:http://stackoverflow.com/questions/1106943/nscalendar-first-day-of-week会有所帮助.基本上你需要将日历的第一周设置为星期一([calendar setFirstWeekday:2]) (2认同)

Joh*_*und 18

只需使用以下三行:

CFAbsoluteTime at = CFAbsoluteTimeGetCurrent();
CFTimeZoneRef tz = CFTimeZoneCopySystem();
SInt32 WeekdayNumber = CFAbsoluteTimeGetDayOfWeek(at, tz);
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢它,但这几乎可以算作对一些新开发者的混淆(这可能是一个邪恶的奖金);) (3认同)
  • 在iOS 8中不推荐使用CFAbsoluteTimeGetDayOfWeek.是否有使用CFCalendar的替代方法? (2认同)

小智 14

这里的许多答案都已弃用.这适用于iOS 8.4,并以字符串和数字的形式为您提供星期几.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"The day of the week: %@", [dateFormatter stringFromDate:[NSDate date]]);

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [gregorian components:NSCalendarUnitWeekday fromDate:[NSDate date]];
int weekday = [comps weekday];
NSLog(@"The week day number: %d", weekday);
Run Code Online (Sandbox Code Playgroud)


Ash*_*lls 10

以下是您在Swift 3中的操作方法,并获得本地化的日期名称......

let dayNumber = Calendar.current.component(.weekday, from: Date()) // 1 - 7
let dayName = DateFormatter().weekdaySymbols[dayNumber - 1]
Run Code Online (Sandbox Code Playgroud)


Ha *_*uan 7

-(void)getdate {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"MMM dd, yyyy HH:mm"];
    NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
    [timeFormat setDateFormat:@"HH:mm:ss"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
    [dateFormatter setDateFormat:@"EEEE"];

    NSDate *now = [[NSDate alloc] init];
    NSString *dateString = [format stringFromDate:now];
    NSString *theDate = [dateFormat stringFromDate:now];
    NSString *theTime = [timeFormat stringFromDate:now];

    NSString *week = [dateFormatter stringFromDate:now];
    NSLog(@"\n"
          "theDate: |%@| \n"
          "theTime: |%@| \n"
          "Now: |%@| \n"
          "Week: |%@| \n"
         , theDate, theTime,dateString,week); 
}
Run Code Online (Sandbox Code Playgroud)