NSCalendar first day of week

Edit: This does not check the edge case where the beginning of the week starts in the prior month. Some updated code to cover this: https://stackoverflow.com/a/14688780/308315 In case anyone is still paying attention to this, you need to use ordinalityOfUnit:inUnit:forDate: and set firstWeekday to 2. (1 == Sunday and 7 == Saturday) Here’s the code: … Read more

All dates between two Date objects (Swift)

Just add one day unit to the date until it reaches the current date (Swift 2 code): var date = startDateNSDate // first date let endDate = NSDate() // last date // Formatter for printing the date, adjust it according to your needs: let fmt = NSDateFormatter() fmt.dateFormat = “dd/MM/yyyy” // While date <= endDate … Read more

Swift 3 – find number of calendar days between two dates

In Swift 5 there is a simple one-liner to get the number of days (or any other DateComponent) between two dates: let diffInDays = Calendar.current.dateComponents([.day], from: dateA, to: dateB).day Note: As pointed out in the comments, this solution measures the 24h periods and therefore requires at least 24h between dateA and dateB.

Number of days in the current month using iOS?

You can use the NSDate and NSCalendar classes: NSDate *today = [NSDate date]; //Get a date object for today’s date NSCalendar *c = [NSCalendar currentCalendar]; NSRange days = [c rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:today]; today is an NSDate object representing the current date; this can be used to work out the number of days in the current … Read more

Swift – check if a timestamp is yesterday, today, tomorrow, or X days ago

Swift 3/4/5: Calendar.current.isDateInToday(yourDate) Calendar.current.isDateInYesterday(yourDate) Calendar.current.isDateInTomorrow(yourDate) Additionally: Calendar.current.isDateInWeekend(yourDate) Note that for some countries weekend may be different than Saturday-Sunday, it depends on the calendar. You can also use autoupdatingCurrent instead of current calendar, which will track user updates. You use it the same way: Calendar.autoupdatingCurrent.isDateInToday(yourDate) Calendar is a type alias for the NSCalendar.

Get day of week using NSDate

Swift 3 & 4 Retrieving the day of the week’s number is dramatically simplified in Swift 3 because DateComponents is no longer optional. Here it is as an extension: extension Date { func dayNumberOfWeek() -> Int? { return Calendar.current.dateComponents([.weekday], from: self).weekday } } // returns an integer from 1 – 7, with 1 being Sunday … Read more