How can I find out whether an NSDate is a business day?

耗尽温柔 提交于 2019-12-24 01:51:04

问题


How can I find out whether an NSDate is a business day? That is to say, whether or not it is a weekend according to the user's current locale and calendar settings - so not hardcoded to just be Monday to Friday?

NSCalendar has a firstWeekday property, but that just seems to be a presentational thing; it's Sunday in the US and Monday in the UK.

EDIT: I'm not worried about holidays, I just want to be able to shade the weekends of a calendar in the same way as the built-in calendar app.


回答1:


Update for iOS 8 and higher:

NSCalendar now contains method - (BOOL)isDateInWeekend:(NSDate *)date

which checks whether a date falls under weekend in a particular calendar & locale.

Old answer

If you only need to shade the weekends, [NSDateComponents weekday] is your friend. This method will return 1 for Sunday and 7 for Saturday.

Fact: Most applications assume weekend = Saturday & Sunday. AFAIK this is correct for all countries using Gregorian Calendar. The only possibility covering all other calendars is to have a local database per calendar/locale and watch for changes. If such a change happens an application update is needed or new data has to be downloaded.

If we are talking about business days (not only weekends), we are talking about something that

  1. has no clear definition (what is a business day changes between companies)
  2. has no specification (for example - date formatting, time zones etc. has internationally accepted specifications)
  3. is often changed by local law (e.g. holidays added)

What you need is to let the users set up your applications for their individual needs, depending on their nationality and employer.




回答2:


You can get if the day is Monday to Friday, but as far as I know, there's no such things as business day for NSDate depending on the location, as for example firstWeekday, so you will need to implement it yourself.




回答3:


Use NSDateComponents.

NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSLog(@"Weekday: %d", dateComponents.weekday);

This will also differentiate whether the device is in a territory where Sunday or Monday are considered to be the first day of the week.



来源:https://stackoverflow.com/questions/17546017/how-can-i-find-out-whether-an-nsdate-is-a-business-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!