Swift - Weekday by current location by currentCalendar()
For the Gregorian calendar, the weekday
property of NSDateComponents
is always
1 for Sunday, 2 for Monday etc.
NSCalendar.currentCalendar().firstWeekday
gives the (index of the) first weekday in the current locale, that could be 1 in USA
and 2 in Bulgaria. Therefore
var dayOfWeek = dateComps.weekday + 1 - calendar.firstWeekday
if dayOfWeek <= 0 {
dayOfWeek += 7
}
is the day of the week according to your locale. As a one-liner:
let dayOfWeek = (dateComps.weekday + 7 - calendar.firstWeekday) % 7 + 1
Update for Swift 3:
let calendar = Calendar.current
var dayOfWeek = calendar.component(.weekday, from: Date()) + 1 - calendar.firstWeekday
if dayOfWeek <= 0 {
dayOfWeek += 7
}
How to get the 'n' weekday of a Date
There is an alternative to get the start of the week which
translates directly to Swift 3:
extension Date {
func getWeekDay(day: Int) -> Date {
let cal = Calendar.current
let comps = cal.dateComponents([.weekOfYear, .yearForWeekOfYear], from: self)
let beginningOfWeek = cal.date(from: comps)!
let nextDate = cal.date(byAdding: .day, value: day, to: beginningOfWeek)!
return nextDate
}
}
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.
Cannot update calendar firstWeekDay Swift 3.0
I managed to solve the issue. Apparently I had to define a new function and update the firstWeekDay property inside that function. :)
Swift - Start day and end day of the week before previous week
Something like this should work:
let cal = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.weekOfYear -= 1
if let date = cal.dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(0)) {
var beginningOfWeek: NSDate?
var weekDuration = NSTimeInterval()
if cal.rangeOfUnit(.CalendarUnitWeekOfYear, startDate: &beginningOfWeek, interval: &weekDuration, forDate: date) {
let endOfWeek = beginningOfWeek?.dateByAddingTimeInterval(weekDuration)
print(beginningOfWeek) // Optional(2015-02-15 05:00:00 +0000)
print(endOfWeek) // Optional(2015-02-22 05:00:00 +0000)
}
}
How to get Monday's date of the current week in swift
I wrote Date extensions to get Date for certain weekday and here is how easy it is to use with Swift 5,
Date.today() // Oct 15, 2019 at 9:21 AM
Date.today().next(.monday) // Oct 21, 2019 at 9:21 AM
Date.today().next(.sunday) // Oct 20, 2019 at 9:21 AM
Date.today().previous(.sunday) // Oct 13, 2019 at 9:21 AM
Date.today().previous(.monday) // Oct 14, 2019 at 9:21 AM
Date.today().previous(.thursday) // Oct 10, 2019 at 9:21 AM
Date.today().next(.thursday) // Oct 17, 2019 at 9:21 AM
Date.today().previous(.thursday,
considerToday: true) // Oct 10, 2019 at 9:21 AM
Date.today().next(.monday)
.next(.sunday)
.next(.thursday) // Oct 31, 2019 at 9:21 AM
And here is Date extension for that,
extension Date {
static func today() -> Date {
return Date()
}
func next(_ weekday: Weekday, considerToday: Bool = false) -> Date {
return get(.next,
weekday,
considerToday: considerToday)
}
func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date {
return get(.previous,
weekday,
considerToday: considerToday)
}
func get(_ direction: SearchDirection,
_ weekDay: Weekday,
considerToday consider: Bool = false) -> Date {
let dayName = weekDay.rawValue
let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() }
assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)")
let searchWeekdayIndex = weekdaysName.firstIndex(of: dayName)! + 1
let calendar = Calendar(identifier: .gregorian)
if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex {
return self
}
var nextDateComponent = calendar.dateComponents([.hour, .minute, .second], from: self)
nextDateComponent.weekday = searchWeekdayIndex
let date = calendar.nextDate(after: self,
matching: nextDateComponent,
matchingPolicy: .nextTime,
direction: direction.calendarSearchDirection)
return date!
}
}
// MARK: Helper methods
extension Date {
func getWeekDaysInEnglish() -> [String] {
var calendar = Calendar(identifier: .gregorian)
calendar.locale = Locale(identifier: "en_US_POSIX")
return calendar.weekdaySymbols
}
enum Weekday: String {
case monday, tuesday, wednesday, thursday, friday, saturday, sunday
}
enum SearchDirection {
case next
case previous
var calendarSearchDirection: Calendar.SearchDirection {
switch self {
case .next:
return .forward
case .previous:
return .backward
}
}
}
}
How can I find the next weekend Swift
First find the number of days to add to NSDateComponents
weekday
property and then You can use dateByAddingComponents(_:toDate:options:)
.
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let todayWeekday = calendar.component(.Weekday, fromDate: today)
let addWeekdays = 7 - todayWeekday // 7: Saturday number
var components = NSDateComponents()
components.weekday = addWeekdays
let nextSaturday = calendar.dateByAddingComponents(components, toDate: today, options: .MatchFirst)
Get weekdays within a month
With the help of this answer, I was able to accomplish this.
let calendar = NSCalendar.currentCalendar()
let normalizedStartDate = calendar.startOfDayForDate(NSDate().startOfMonth)
let normalizedEndDate = calendar.startOfDayForDate(NSDate().endOfMonth)
var dates = [normalizedStartDate]
var currentDate = normalizedStartDate
repeat {
currentDate = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: 1, toDate: currentDate, options: .MatchNextTime)!
dates.append(currentDate)
} while !calendar.isDate(currentDate, inSameDayAsDate: normalizedEndDate)
let weekdays = dates.filter { !calendar.isDateInWeekend($0) }
weekdays.forEach { date in
print(NSDateFormatter.localizedStringFromDate(date, dateStyle: .FullStyle, timeStyle: .NoStyle))
}
And it works!
Monday, February 1, 2016
Tuesday, February 2, 2016
Wednesday, February 3, 2016
Thursday, February 4, 2016
Friday, February 5, 2016
Monday, February 8, 2016
Tuesday, February 9, 2016
Wednesday, February 10, 2016
Thursday, February 11, 2016
Friday, February 12, 2016
Monday, February 15, 2016
Tuesday, February 16, 2016
Wednesday, February 17, 2016
Thursday, February 18, 2016
Friday, February 19, 2016
Monday, February 22, 2016
Tuesday, February 23, 2016
Wednesday, February 24, 2016
Thursday, February 25, 2016
Friday, February 26, 2016
Monday, February 29, 2016
Related Topics
How to Detect If My Device Is an iPhone x in Swift 4
How to Open Application Using Url
iOS 8 [Uiapplication Sharedapplication].Scheduledlocalnotifications Empty
Does "Let _ = ..." (Let Underscore Equal) Have Any Use in Swift
How to Fix Broken Transform-Origin on iOS11 and Macos10.12 Safari
Perform "Use Photo" Button on Custom Image Picker Overlay
In What Format Is This Date String
iOS Swift Streaming App Does Not Play Music in Background Mode
How to Programmatically Delete My Own iOS App
iOS - Running Background Task for Update User Location Using Swift
Notification in Swift Every Day at a Set Time
Firebase Cloud Messaging Cannot Parse Topic Name
Error | [Ios] File Patterns: the 'Source_Files' Pattern Did Not Match Any File
Uipageviewcontroller Setviewcontrollers, UIpagecontrol Not Showing Right Current Number