Search code examples
swiftdatedatetimenscalendarnsdatecomponents

Swift - nextDate() search by day of year


Hoping for some help on this one. I'm trying to search (forwards and backwards) to find the next date that matches the day of the year

So, for instance I have a day value of 300, I know we are currently on day 237 of this year (as of writing this post, 25/08/18!), and I want to search backwards to find the previous occurrence of the 300th day of a year, and format a date from it.

I'm already extracting the 'day of year' from date using a small Date extension:

extension Date {
    var dayOfYear: Int {
        return Calendar.current.ordinality(of: .day, in: .year, for: self)!
    }
}

Using the Calendar.nextDate() function I can search to match '.day' , but that's obviously day of month, not year:

let potentialSartDate = (Calendar.current as NSCalendar).nextDate(after: nowDate, matching: .day, value: dayOfYearValueToMatch, options: [.matchNextTime, .searchBackwards])!

Does anyone have any pointers, or approach, of how to perform a search like this build a date out of the result?

Thanks in advance!

Emile


Solution

  • You can get the current year component from today and use the Calendar date(from: DateComponents) method to get the 300th day of the year as follow:

    extension Calendar {
        static let iso8601 = Calendar(identifier: .iso8601)
    }
    extension Date {
        var year: Int {
            return Calendar.current.component(.year, from: self)
        }
        var last300ThDayOfYear: Date {
            return Calendar.current.date(from: DateComponents(calendar: .iso8601, year: dayOfYear > 300 ? year  : year - 1, day: 300))!
        }
        var dayOfYear: Int {
            return Calendar.current.ordinality(of: .day, in: .year, for: self)!
        }
    }
    

    let date = Date().last300ThDayOfYear  // "Oct 27, 2017 at 12:00 AM"
    print(date.dayOfYear)  // 300