You can get the date for the last day of the current year in Swift using the Calendar
and DateComponents
classes. Here's the code:
main.swift214 chars5 lines
In this code, we first create an instance of the Calendar
class using the current
class property. We then use the component(_:from:)
method of the Calendar
instance to extract the current year from the Date()
instance.
Next, we create an instance of the DateComponents
class, specifying the current year as the year
component, 12
as the month
component (December), and 31
as the day
component.
Finally, we use the date(from:)
method of the Calendar
instance to create a Date
instance representing the last day of the current year. We force-unwrap the result using the !
operator, since we know that the combination of components we've specified will always produce a valid date.
gistlibby LogSnag