Home > OS >  Creating a Variable that represents the start of the Current year?, Swiftui
Creating a Variable that represents the start of the Current year?, Swiftui

Time:10-07

Just wondering how to get to create a variable in which it will always hold the beginning of the current year. So for right now january 1, 2022.

let begOfYear = ...

CodePudding user response:

You can use Calendar component method to get the year of a date and use it to initialize a new DateComponents object with the desired calendar. Then you just need to get the date property from that DateComponents object:

let calendar = Calendar.current
let currentYear = calendar.component(.year, from: Date())  // 2022
let firstDayOfYear = DateComponents(calendar: calendar, year: currentYear).date  // "Jan 1, 2022 at 12:00 AM"

You can also extend Date as follow:

extension Date {
    func year(using calendar: Calendar = .current) -> Int {
        calendar.component(.year, from: self)
    }
    func firstDayOfYear(using calendar: Calendar = .current) -> Date? {
        DateComponents(calendar: calendar, year: year(using: calendar)).date
    }
}

Usage:

Date().year()            // 2022
Date().firstDayOfYear()  // "Jan 1, 2022 at 12:00 AM"

CodePudding user response:

I admit that I prefer Leo's solution.

But if you are looking for an one-liner (4 lines for clarity) tell the calendar to search backwards for the date components month:1, day:1, hour:0, minute:0, second:0 from now

let begOfYear = Calendar.current.nextDate(
    after: .now,
    matching: DateComponents(month: 1, day: 1),
    matchingPolicy: .nextTime,
    direction: .backward
)
  • Related