To get the date for the last day of the current month in Swift, you can use the following code:
main.swift240 chars5 lines
Here, we first create a Date
object for the current date using the Date()
initializer. We then create a Calendar
object that represents the current calendar using the Calendar.current
class property.
Next, we create a DateComponents
object that represents the components of the date we want to create. We set the year
and month
components to the current year and month, respectively, and set the day
component to 0
. When we set the day
component to 0
, we are actually getting the last day of the previous month.
Finally, we use the date(from:components:)
method of the calendar to create a Date
object for the last day of the current month. We force unwrap the result because we know that it will never be nil
.
gistlibby LogSnag