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

You can get the first day of the current decade by creating a new date using the current year and then using a Calendar instance to set the year to the first year of the decade. Assuming the decade starts at 2010, you can use the following code:

main.swift
let calendar = Calendar.current
let components = calendar.dateComponents([.year], from: Date())
let year = components.year!

let startYear = (year / 10) * 10
let startDateComponents = DateComponents(year: startYear, month: 1, day: 1)

if let startDate = calendar.date(from: startDateComponents) {
    print(startDate)
} else {
    print("Unable to create date")
}
364 chars
13 lines

This code creates a DateComponents object with the year set to the first year of the current decade (e.g. 2010 if the current year is 2018). It then creates a new date using the Calendar instance and the DateComponents object. If successful, it will print the date for the first day of the current decade. Otherwise, it will print an error message.

gistlibby LogSnag