9 Replies Latest reply: Dec 9, 2008 5:15 PM by DarelRex
aapl.crox Level 1 (0 points)
How to get day of week from NSDate?
  • GazF Level 1 (40 points)
    something like this:

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest];

    NSInteger weekday = [weekdayComponents weekday];
    // weekday 1 = Sunday for Gregorian calendar

    [gregorian release];
  • brec Level 1 (15 points)
    I entered "day of week" into the Xcode's Documentation search box and the first hit looks like it might be useful: the Calendrical Calculations article in Date and Time Programming Guide for Cocoa.
  • Steve Herman1 Level 4 (2,545 points)
    Here's a way to get the name of the weekday as an NSString if you've already got an NSDate...

    NSDate * testDate = [NSDate date];
    NSString * weekdayString = [testDate descriptionWithCalendarFormat:@"%A" timeZone:nil
    locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
    NSLog(@"Day of the week: %@", weekdayString);

    The output is something like:

    Day of the week: Monday

    You can use a lower-case "%a" as the descriptionWithCalendarFormat if you just want the three character weekday abbreviation ("Mon", "Tue", "Wed", etc).

  • GazF Level 1 (40 points)
    If you're developing for the iPhone, NSDate's descriptionWithCalendarFormat isn't available. (for some reason..)
  • jjss2810 Level 1 (0 points)
    For the iphone this code will work:

    - (NSString *)getDayOfTheWeek:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]
    initWithDateFormat:@"%A" allowNaturalLanguage:NO] autorelease];
    NSString *formattedDateString = [dateFormatter stringFromDate:date];
    return formattedDateString;

  • DarelRex Level 1 (0 points)
    How about this:

    NSString *myString=[myDate descriptionWithCalendarFormat:"%w" timezone:nil locale:nil] ;

    That should return the string "0" for Sunday, "1" for Monday, etc.
  • DarelRex Level 1 (0 points)
    Let's try that again! Formatted correctly this time:

    How about this:

    NSString *myString=\[myDate descriptionWithCalendarFormat:"%w" timezone:nil locale:nil\] ;

    That should return the string "0" for Sunday, "1" for Monday, etc.
  • briyu Level 1 (100 points)
    I like this approach. I've been looking for something like this to use in one of my applications, and I'm surprised I didn't think of this before.
  • DarelRex Level 1 (0 points)
    I forgot the at-sign and misspelled timeZone -- here is the corrected version:

    NSString *myString=\[myDate descriptionWithCalendarFormat:@"%w" timeZone:nil locale:nil\] ;

    Message was edited by: DarelRex