Skip to content

Instantly share code, notes, and snippets.

@macserv
Last active October 31, 2019 22:22
Show Gist options
  • Save macserv/de014159a1376df015a22016228534a9 to your computer and use it in GitHub Desktop.
Save macserv/de014159a1376df015a22016228534a9 to your computer and use it in GitHub Desktop.
Date Extensions for First and Last Day of Month
extension Date
{
var startOfMonth : Date?
{
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month], from: self)
let firstDayDate = calendar.date(from: components)
return firstDayDate
}
var startOfNextMonth : Date?
{
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month], from: self)
components.setValue((components.month! + 1), for: .month)
let firstDayDateOfNextMonth = calendar.date(from: components)
return firstDayDateOfNextMonth
}
var endOfMonth : Date?
{
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month], from: self)
components.setValue((components.month! + 1), for: .month)
components.setValue(0, for: .day)
let lastDayDate = calendar.date(from: components)
return lastDayDate
}
}
let today = DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .none)
let firstDay = DateFormatter.localizedString(from: Date().startOfMonth!, dateStyle: .medium, timeStyle: .none)
let lastDay = DateFormatter.localizedString(from: Date().endOfMonth!, dateStyle: .medium, timeStyle: .none)
let nextMonth = DateFormatter.localizedString(from: Date().startOfNextMonth!, dateStyle: .medium, timeStyle: .none)
print("""
\(today) is today's date.
\(firstDay) is the first day of this month.
\(lastDay) is the last day of this month.
\(nextMonth) is the first day of next month.
""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment