get the date for the first day of the current century in swift

main.swift
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: Date())
let firstYearOfCentury = (currentYear / 100) * 100
let startDateComponent = DateComponents(year: firstYearOfCentury, month: 1, day: 1)
let startDate = calendar.date(from: startDateComponent)!
282 chars
6 lines

In this code, we first create an instance of the Calendar class, which we'll use to manipulate dates. We then use the component(_:from:) method to get the current year. We calculate the first year of the current century by dividing the current year by 100, then multiplying by 100. We then create a DateComponents instance representing January 1st of the first year of the current century, and create a Date instance from those components using the date(from:) method of the Calendar class. This gives us the date for the first day of the current century.

gistlibby LogSnag