first and last day of the current month in swift
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Swift, the cleanest way to get the first and last day of the current month is to ask Calendar for the month interval containing today's date. This is better than hard-coding month lengths because Calendar already handles leap years, varying month sizes, and locale-sensitive calendar rules.
The Easiest Modern Approach
Calendar.dateInterval(of:for:) returns the start date of the month and the exclusive end date of that month.
This is a strong default because it avoids manual date math.
Getting the Last Calendar Day
Sometimes you do not want the last moment of the month. You want the date representing the final calendar day. A common pattern is to subtract one day from the first day of the next month:
That is usually what people mean by "last day of the month."
Building the First Day With Components
You can also compute the first day manually by extracting the year and month:
This works, but for both first and last day together, dateInterval(of:for:) is usually the simpler API.
Why Calendar APIs Matter
Dates are not just timestamps. Once you start asking calendar questions such as "first day of this month," you should use calendar-aware APIs instead of raw second offsets.
That matters because:
- months do not all have the same length
- daylight saving changes can affect day boundaries
- non-Gregorian calendars exist
Calendar is designed for exactly this kind of work, so let it perform the date arithmetic rather than re-creating it manually.
This becomes even more important in apps that support multiple locales or calendars, because the "current month" is a calendar concept, not just a hard-coded number of seconds.
Formatting the Result
If you want to display the dates to users, format them with DateFormatter:
That separates the calculation from the user-facing representation.
It also keeps your date logic testable. The code that finds the month boundaries should not depend on whatever display format the UI happens to use today.
Common Pitfalls
- Hard-coding month lengths instead of using
Calendar. - Confusing the exclusive month end with the last calendar day.
- Using raw timestamp arithmetic for calendar questions.
- Ignoring time zone or locale effects when the app displays dates to users.
- Forgetting that
dateInterval(of:for:)can returnniland should be handled safely.
Summary
- '
Calendar.dateInterval(of: .month, for: ...)is the easiest way to get the current month boundaries.' - The interval start gives the first day of the month.
- Subtract one day from the interval end if you need the last calendar day.
- Use
Calendarfor calendar logic andDateFormatterfor display. - Avoid manual month-length logic because the calendar APIs already handle the edge cases.

