Skip to content

Instantly share code, notes, and snippets.

@uy
Created June 1, 2022 09:55
Show Gist options
  • Save uy/9f91acd6cc46446c8637a41168b53be2 to your computer and use it in GitHub Desktop.
Save uy/9f91acd6cc46446c8637a41168b53be2 to your computer and use it in GitHub Desktop.
get days in given date's month
import Foundation
struct MCalendarDate {
let weekOfYear: Int
let weekday: Int
let day: Int
let month: Int
let year: Int
let date: Date
}
struct MCalendarWeek {
let weekOfYear: Int
var days: [MCalendarDay]
}
struct MCalendarDay {
let weekday: Int
let day: Int
let month: Int
let year: Int
let date: Date
}
let date = Date()
var calendar = Calendar(identifier: .iso8601)
calendar.locale = Locale(identifier: "tr_TR")
var days: [MCalendarDate] = []
var ds: [MCalendarWeek] = []
var firstDayComponents = calendar.dateComponents([.year, .month], from: date)
let firstDay = calendar.date(from: firstDayComponents)!
let range = calendar.range(of: .day, in: .month, for: firstDay)!
var checkOfWeekOfYear = -1
var calWeek: MCalendarWeek?
for index in 0..<range.count {
let d = calendar.date(byAdding: .day, value: index, to: firstDay)!
let weekOfYear = calendar.component(.weekOfYear, from: d)
let weekday = (calendar.component(.weekday, from: d) - 1 + 6) % 7
let day = calendar.component(.day, from: d)
let month = calendar.component(.month, from: d)
let year = calendar.component(.year, from: d)
days.append(MCalendarDate(weekOfYear: weekOfYear, weekday: weekday, day: day, month: month, year: year, date: d))
if checkOfWeekOfYear != weekOfYear {
checkOfWeekOfYear = weekOfYear
if calWeek != nil {
ds.append(calWeek!)
calWeek = nil
}
calWeek = MCalendarWeek(weekOfYear: weekOfYear, days: [])
}
calWeek?.days.append(MCalendarDay(weekday: weekday, day: day, month: month, year: year, date: d))
}
for d in ds {
print("Week of year: \(d.weekOfYear)")
for dd in d.days {
print(dd)
}
}
//for d in days {
// print(d)
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment