Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract all date components from a Date

(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.

like image 469
Kqtr Avatar asked Nov 05 '25 02:11

Kqtr


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())
like image 185
Dávid Pásztor Avatar answered Nov 07 '25 07:11

Dávid Pásztor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!