I need to display current month/first weekday on the xAxis of the graph. Can anyone help me out with this? How can I get current month's first day of all weeks.
You can create a DateComponents
with the components:
year: someYear,
month: someMonth,
weekday: someCalendar.firstWeekday,
weekOfMonth: n
use Calendar.date(from:)
to get the Date
corresponding to those components. Now you just need to vary n
from 1 to 5, and put each result into an array.
var firstsOfWeek = [Date]()
let year = 2020
let month = 10
let calendar = Calendar.current
for n in 1...5 {
let dc = DateComponents(
year: year,
month: month,
weekday: calendar.firstWeekday,
weekOfMonth: n
)
firstsOfWeek.append(calendar.date(from: dc)!)
}
However, date(from:)
will return a date that is not in someMonth
if the first week of someMonth
is only partially inside someMonth
. For example, (assuming the week starts on a Sunday) the first week of October 2020 starts on 27 September, and date(from:)
will give you that date if you ask it what the date corresponding to weekOfMonth: 1
is.
If you don't want that date. simply add a check to only include the start of month if it is a start of week as well, and change the for loop range to 2...5
:
let firstDayOfMonth = calendar.date(from: DateComponents(year: year, month: month))!
if calendar.component(.weekday, from: firstDayOfMonth) == calendar.firstWeekday {
firstsOfWeek.append(firstDayOfMonth)
}
for n in 2...5 {
...
But do note that if you do this, the resulting array will sometimes have 4 elements, and sometimes 5 elements.