How to Use Enumeratedate in Swift 3 to Find All Sundays the Last 50 Years

How to use enumerateDate in Swift 3 to find all Sundays the last 50 years?

The following code will print the last 50 years of Sundays starting with the most recent Sunday.

let cal = Calendar.current
// Get the date of 50 years ago today
let stopDate = cal.date(byAdding: .year, value: -50, to: Date())!

// We want to find dates that match on Sundays at midnight local time
var comps = DateComponents()
comps.weekday = 1 // Sunday

// Enumerate all of the dates
cal.enumerateDates(startingAfter: Date(), matching: comps, matchingPolicy: .previousTimePreservingSmallerComponents, repeatedTimePolicy: .first, direction: .backward) { (date, match, stop) in
if let date = date {
if date < stopDate {
stop = true // We've reached the end, exit the loop
} else {
print("\(date)") // do what you need with the date
}
}
}

how can we get the number of sundays on an given month ? ( swift )

func getNumberOfDaysInMonth (month : Int , Year : Int) -> Int{

let dateComponents = NSDateComponents()
dateComponents.year = Year
dateComponents.month = month

let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)!

let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)

let numDays = range.length

// New code starts here:

var numberOfSundays = 0

let dateFormatter = NSDateFormatter()

for day in 1...numDays {

dateComponents.day = day

let date = calendar.dateFromComponents(dateComponents)!
dateFormatter.dateFormat = "EEEE"
let dayOfWeek = dateFormatter.stringFromDate(date) // Get day of week

if dayOfWeek == "Sunday" { // Check if it's a Sunday
numberOfSundays += 1
}
}

return numDays - numberOfSundays
}

What is the most effective way to iterate over a date range in Swift?

If I understand your question correctly, the user will check off some weekdays and provide a duration as a number of days.

Assuming you have the selected weekdays in an array and the duration, you can get the list of matching dates as follows:

// User selected weekdays (1 = Sunday, 7 = Saturday)
var selectedWeekdays = [2, 4, 6] // Example - Mon, Wed, Fri
var duration = 10 // Example - 10 days

let calendar = Calendar.current
var today = Date()
let dateEnding = calendar.date(byAdding: .day, value: duration, to: today)!

var matchingDates = [Date]()
// Finding matching dates at midnight - adjust as needed
let components = DateComponents(hour: 0, minute: 0, second: 0) // midnight
calendar.enumerateDates(startingAfter: today, matching: components, matchingPolicy: .nextTime) { (date, strict, stop) in
if let date = date {
if date <= dateEnding {
let weekDay = calendar.component(.weekday, from: date)
print(date, weekDay)
if selectedWeekdays.contains(weekDay) {
matchingDates.append(date)
}
} else {
stop = true
}
}
}

print("Matching dates = \(matchingDates)")

How to get all days in current week in swift

To get the weekdays of the week, it is:

let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let days = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
.compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
.filter { !calendar.isDateInWeekend($0) }

To display that as "Thursday = 82", it is

let formatter = DateFormatter()
formatter.dateFormat = "eeee' = 'D"
for date in days {
print(formatter.string(from: date))
}

Or

let strings = days.map { formatter.string(from: $0) }

How to get dates for every thursday or other day of week in specific month?

Short solution:


// Get current calendar and current date
let calendar = Calendar.current
let now = Date()
// Get the current date components for year, month, weekday and weekday ordinal
var components = calendar.dateComponents([.year, .month, .weekdayOrdinal, .weekday], from: now)
// get the range (number of occurrences) of the particular weekday in the month
let range = calendar.range(of: .weekdayOrdinal, in: .month, for: now)!
// Loop thru the range, set the components to the appropriate weekday ordinal and get the date
for ordinal in range.lowerBound..


Be aware that print prints dates always in UTC.

Edit:

range(of: .weekdayOrdinal, in: .month does not work, it returns 1..<6 regardless of the date.

This is a working alternative. It checks if the date exceeds the month bounds

// Get current calendar and date for 2017/4/13
let calendar = Calendar.current
let april13Components = DateComponents(year:2017, month:4, day:13)
let april13Date = calendar.date(from: april13Components)!

// Get the current date components for year, month, weekday and weekday ordinal
var components = calendar.dateComponents([.year, .month, .weekdayOrdinal, .weekday], from: april13Date)

// Loop thru the range, set the components to the appropriate weekday ordinal and get the date
for ordinal in 1..<6 { // maximum 5 occurrences
components.weekdayOrdinal = ordinal
let date = calendar.date(from: components)!
if calendar.component(.month, from: date) != components.month! { break }
print(calendar.date(from: components)!)
}

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
}
}

Unable to cast object of type 'system.data.datatable' to type

DataView.Table returns you the underlying source DataTable, in your case this source table is of type AvailDataTable.

http://msdn.microsoft.com/en-us/library/system.data.dataview.table.aspx

Whereas DefaultView.ToTable constructs a new instance of a DataTable based on the rows in the current view.

Subtle difference here but ToTable returns you a generic DataTable object not your specific DataTable type

http://msdn.microsoft.com/en-us/library/a8ycds2f.aspx



Related Topics



Leave a reply



Submit