How to Get the Day of the Week With Foundation

How do I get the day of the week with Foundation?

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

outputs current day of week as a string in locale dependent on current regional settings.

To get just a week day number you must use NSCalendar class:

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];

How to get the day of week from a given number

Since this has become the accepted answer, I'll post the "right" solution here too. Credits to Rob's answer.

The whole thing can simply be achieved using the [shortWeekdaySymbols][1] method of NSDateFormatter, so the full solution boils down to

- (NSString *)stringFromWeekday:(NSInteger)weekday {
NSDateFormatter * dateFormatter = [NSDateFormatter new];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
return dateFormatter.shortWeekdaySymbols[weekday];
}

Original answer

Beware, you're passing a pointer to NSNumber to a method that requires a NSInteger.
The compiler is not warning you since a pointer is indeed an integer, just not the one you would expect.
Consider this simple test:

- (void)foo:(NSInteger)a {
NSLog(@"%i", a);
}

- (void)yourMethod {
[self foo:@1]; // @1 is the boxed expression for [NSNumber numberWithInt:1]
}

This prints something like 185035664, which is the pointer value, i.e. NSNumber * when cast to NSInteger.

You should either use [dayOfWeek integerValue] or directly turn dayOfWeek into a NSInteger in your method signature.

Also I think you're getting something else wrong: from the doc of setWeekday:

Sets the number of weekday units for the receiver. Weekday units are
the numbers 1 through n, where n is the number of days in the week.
For example, in the Gregorian calendar, n is 7 and Sunday is
represented by 1
.

Sunday is 1, so you'd better check the correspondence with your representation too.

How to find weekday from today's date using NSDate?

NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:NSCalendarUnitWeekday fromDate:[NSDate date]];
return [comp weekday]; // 1 = Sunday, 2 = Monday, etc.

See @HuguesBR's answer if you just need the weekday without other components (requires iOS 8+).

NSInteger weekday = [[NSCalendar currentCalendar] component:NSCalendarUnitWeekday 
fromDate:[NSDate date]];

(If you don't get a correct answer, check if you have mistyped NSCalendarUnitWeekday with other week-related components like NSCalendarUnitWeekdayOrdinal, etc.)


Swift 3:

let weekday = Calendar.current.component(.weekday, from: Date())
// 1 = Sunday, 2 = Monday, etc.

How to get Day number of week from NSDate

It will fetch you the day number i.e. 2. The day number are always same for every week. (1-7).

As pointed by Vyachaslav Gerchicov, the weekday number starts from Sunday

i.e Sunday is 1, Monday is 2... Saturday is 7

//Assuming your calendar is initiated like this
NSCalendar *_calendar = [NSCalendar currentCalendar];

//Fetch the day number
NSInteger day = [_calendar component:NSCalendarUnitWeekday fromDate:date];

Explore NSCalendar for more details here


For Swift 5.x

let day = Calendar.current.component(.weekday, from: date)

Explore Calendar for more details here

Get name of the day in a week from the day number. (iOS)

Let's start by getting the names of the days:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSArray *daySymbols = dateFormatter.standaloneWeekdaySymbols;

Now, this is an array of weekday names where at index 0 is Sunday, therefore you will have to convert your indices.

NSInteger dayIndex = 1; // 1 = Monday, ... 7 = Sunday
NSString *dayName = daySymbols[dayIndex % 7];

Objective C - How can i get the weekday from NSDate?

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:.

Using Apple Foundation Calendar properly

A couple of observations:

  1. When iterate through weekdays, you want to go from 1 through 7, because, “Day, week, weekday, month, and year numbers are generally 1-based...” Date and Time Programming Guide: Date Components and Calendar Units. You can use range(of:in:for:), maximumRange(of:), etc., to find the range of possible values.

  2. The weekday values from 1 through 7 do not mean “first day of the week”, “second day of the week”, etc. They refer to specific days of the week, e.g. for .iso8601, “Sun” is 1, “Mon” is 2, etc.

  3. Make sure when you use weekOfYear, you use yearForWeekOfYear:

    let calendar = Calendar(identifier: .iso8601)
    let firstOfWeek = DateComponents(calendar: calendar, weekOfYear: 6, yearForWeekOfYear: 2019).date!
  4. Your code is iterating through the weekdays. Consider this code that enumerates all of the days of the week for the sixth week of 2019 (i.e. the week starting Monday, February 4th and ending Sunday, February 10th):

    let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: firstOfWeek)!
    let daysOfTheWeek = Dictionary(uniqueKeysWithValues: zip(weekdays, calendar.weekdaySymbols))

    for weekday in weekdays {
    let date = DateComponents(calendar: calendar, weekday: weekday, weekOfYear: 6, yearForWeekOfYear: 2019).date!
    print("The", daysOfTheWeek[weekday]!, "in the 6th week of 2019 is", formatter.string(from: date))
    }

    That results in:

    The Sun in the 6th week of 2019 is Sunday, February 10, 2019

    The Mon in the 6th week of 2019 is Monday, February 4, 2019

    The Tue in the 6th week of 2019 is Tuesday, February 5, 2019

    The Wed in the 6th week of 2019 is Wednesday, February 6, 2019

    The Thu in the 6th week of 2019 is Thursday, February 7, 2019

    The Fri in the 6th week of 2019 is Friday, February 8, 2019

    The Sat in the 6th week of 2019 is Saturday, February 9, 2019

    This is effectively what your code does and why you’re not seeing what you expected.

  5. If you want iterate through the seven days of the week in order, just get the start of the week and then offset it from there:

    let calendar = Calendar(identifier: .iso8601)
    let startOfWeek = DateComponents(calendar: calendar, weekOfYear: 6, yearForWeekOfYear: 2019).date!

    for offset in 0 ..< 7 {
    let date = calendar.date(byAdding: .day, value: offset, to: startOfWeek)!
    print(offset, "->", formatter.string(from: date))
    }

    That results in:

    0 -> Monday, February 4, 2019

    1 -> Tuesday, February 5, 2019

    2 -> Wednesday, February 6, 2019

    3 -> Thursday, February 7, 2019

    4 -> Friday, February 8, 2019

    5 -> Saturday, February 9, 2019

    6 -> Sunday, February 10, 2019

  6. You asked:

    I need to get the first day of a given week of year.

    Probably needless to say at this point, but just omit the weekday:

    let startOfWeek = DateComponents(calendar: calendar, weekOfYear: 6, yearForWeekOfYear: 2019).date!

Also see Date and Time Programming Guide: Week-Based Calendars.

Get day of week using NSDate

What you are looking for (if I understand the question correctly) is NSCalendarUnit.CalendarUnitWeekday. The corresponding property of NSDateComponents is weekday.

Note also that your date format is wrong (the
full specification can be found here: http://unicode.org/reports/tr35/tr35-6.html).

The function can be simplified slightly, using automatic type inference, also you use variables a lot where constants are sufficient.
In addition, the function should return an optional which is nil
for an invalid input string.

Updated code for Swift 3 and later:

func getDayOfWeek(_ today:String) -> Int? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
guard let todayDate = formatter.date(from: today) else { return nil }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
return weekDay
}

Example:

if let weekday = getDayOfWeek("2014-08-27") {
print(weekday)
} else {
print("bad input")
}

Original answer for Swift 2:

func getDayOfWeek(today:String)->Int? {

let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
if let todayDate = formatter.dateFromString(today) {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
let weekDay = myComponents.weekday
return weekDay
} else {
return nil
}
}

how to console log day of the week after it the days left untill the end of the week?

What I did is created an array of the days of the week in order and then looped through that to add the day you are looking for and all days after that to a new array.

const daysOfWeek = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
let currentDay = prompt("Enter day of week:");
while (!daysOfWeek.includes(currentDay)) {
currentDay = prompt("Invalid day. Enter day of week:").toLowerCase();
}
let currentDayPassed = false;
const daysLeft = [];
for (let i = 0; i < daysOfWeek.length; i++) {
if (daysOfWeek[i] === currentDay) {
currentDayPassed = true;
}
if (currentDayPassed) {
daysLeft.push(daysOfWeek[i]);
}
}
console.log(daysLeft);


Related Topics



Leave a reply



Submit