11

I need to be able to get the weekday from nsdate, i have the following code and it always return 1. I tried to change the month, i tried everything from 1 to 12 but the result of the week day is always 1.

NSDate *date2 = [[NSDate alloc] initWithString:[NSString stringWithFormat:@"%d-%d-%d", 2010, 6, 1]];
unsigned units2 = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSCalendar *calendar2 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components2 = [calendar2 components:units2 fromDate:date2];
int startWeekDay = [components2 weekday];
[date2 release];
[calendar2 release];
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • Possible duplicate of [How do I get the day of the week with Cocoa Touch?](http://stackoverflow.com/questions/4269093/how-do-i-get-the-day-of-the-week-with-cocoa-touch) – Suhaib Oct 05 '16 at 03:34

7 Answers7

43

Creating an NSDateFormatter that only contains the weekday will do what you want.

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

If you need internationalization, the NSDateFormatter can be sent a locale, which will give the proper translation.

The date formatters are controlled through this standard: Unicode Date Formats

Jon Shier
  • 12,200
  • 3
  • 35
  • 37
  • I think the OP wants an integer of the day of the week (for example, 1 = Monday, 2 = Tuesday, 3 = Wednesday, etc). – dreamlax Aug 19 '10 at 21:11
  • 2
    If you want the integer you just a set: [weekday setDateFormat: @"e"]; You also should set NSLocale... eg: NSLocale *deLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"] autorelease]; [weekday setLocale:deLocale]; Otherwise Thursday might be 5 instead of 4, if the starting day of the week is Sunday or Monday.. – Max B. Jan 12 '12 at 20:14
6

Edit for Mac:

The format of the string has to be —YYYY-MM-DD HH:MM:SS ±HHMM according to the docs, all fields mandatory

Old answer (for iPhone and tested on simulator):

There is no (public) -initWithString: method in NSDate, and what you get returned is not what you expect.

Use a properly configured (you need to give the input format) NSDateFormatter and -dateFromString:.

Eiko
  • 25,601
  • 15
  • 56
  • 71
0

I'm using Xcode 6.4

There are many ways to setup an NSDate. I won't go over that here. You've done it one way, using a string (A method I avoid due to it being very vulnerable to error), and I'm setting it another way. Regardless, access your components weekday or setDay methods.

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekday|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond) fromDate:[NSDate date]];
    NSDate *date = [calendar dateFromComponents:components];

this way, you can get or set any of these components like this:

[components weekday] //to get, then doSomething
[components setDay:6]; //to set

and, of course, set NSDate *date = [calendar dateFromComponents:components];only after you've changed the components.

I added in the extra local and other components for context in case you'd like to set those too.

It's free code, don't knock it.

jungledev
  • 4,195
  • 1
  • 37
  • 52
0

I solved the problem, The problem was that the format of my date string was wrong:

NSDate *date = [[NSDate alloc] initWithString:[NSString stringWithFormat:@"%d-%d-%d 10:45:32 +0600", selectedYear, selectedMonth, selectedDay]];

and since i don't care about the time i randomly pass a time to the end of the string

aryaxt
  • 76,198
  • 92
  • 293
  • 442
0

Anyone coming here looking for a more recent Swift 4 solution:

extension Date {

    func getDayOfWeek() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.locale = Locale(identifier: "en_US")
        dateFormatter.setLocalizedDateFormatFromTemplate("EEEE")

        return dateFormatter.string(from: self)
    }
}

let inputString = "2018-04-16T15:47:39.000Z"

let result = inputString.getDayOfWeek()

result = Monday

JaredH
  • 2,338
  • 1
  • 30
  • 40
0

Most upvoting answer in Swift 3.

let formatter = DateFormatter()
formatter.dateFormat = "EEEE"
print("The day of the week is \(formatter.string(from: Date()))")
Allen
  • 2,979
  • 1
  • 29
  • 34
0

I used the following website which helped with setting up the string to retrieve the format I wanted on my date

Coder Wall - Guide to objective c date formatting

Roger Perez
  • 2,807
  • 29
  • 31