Swift 3.0 Xcode8 beta 4 how to fix Calendar.current.date

568 Views Asked by At

Evening, I really don't know how to convert this:

let birthDay = Calendar.current.date(era: 1, year: year, month: moth, day: day, hour: 0, minute: 0, second: 0, nanosecond: 0)

Into this:

Calendar.current.date(from: <DateComponents>)

Any tips?

This is what I did:

let dateComponet = DateComponents(timeZone: nil, era: 1, year: year, month: month, day: day, hour: 0, minute: 0, second: 0, nanosecond: 0)
let birthDay = Calendar.current.date(from: dateComponet)

Is there a shorter way?

Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

Yes you can pass only the components you want when using that initializer, along with the current calendar and get the date property from the datecomponents object:

DateComponents

public init(calendar: Calendar? = default,
            timeZone: TimeZone? = default,
            era: Int? = default,
            year: Int? = default,
            month: Int? = default,
            day: Int? = default,
            hour: Int? = default,
            minute: Int? = default,
            second: Int? = default,
            nanosecond: Int? = default,
            weekday: Int? = default,
            weekdayOrdinal: Int? = default,
            quarter: Int? = default,
            weekOfMonth: Int? = default,
            weekOfYear: Int? = default,
            yearForWeekOfYear: Int? = default)

let birthDay = DateComponents(calendar: .current, year: 2016, month: 8, day: 9).date!   // "Aug 9, 2016, 12:00 AM"