get the date for the last day of the current year in swift

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.swift
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: Date())
let components = DateComponents(year: currentYear, month: 12, day: 31)
let lastDayOfYear = calendar.date(from: components)!
214 chars
5 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