Extract all date components from a Date

Viewed 288

(I was surprised that I could not find this question asked anywhere, it sounds so basic. I might be missing something...)

Is there a way to create a DateComponents() object that exactly matches a Date/NSDate object (date, time, calendar, timeZone), without having to specify all the components we want to include?

Example of a concrete use case: the UNCalendarNotificationTrigger init method takes DateComponents as an argument, and we'd like to set that notification to a specific date and time kept as a Date/NSDate object, whose dateComponents we therefore need to extract.

1 Answers

You can use Calendar.dateComponents(in:,from:) to achieve your goals. This way you only need to supply the TimeZone and can extract all DateComponents from a Date object.

let components = Calendar.current.dateComponents(in: TimeZone.current, from: Date())
Related