Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding 'wrappingComponents' in date(byAdding:to:wrappingComponents:) method

Tags:

ios

swift

According to Apple Doc, the 'wrappingComponents' parameter serve this purpose:

If true, the component should be incremented and wrap around to zero/one on overflow, and should not cause higher components to be incremented. The default value is false.

What I'm having trouble understanding is the 'overflow' part. What is this overflow and when does this overflow happen? Apple Doc currently does not explain this part in its documentation.

Thanks for your answer in advance.

like image 734
Junsu Kim Avatar asked Sep 13 '26 16:09

Junsu Kim


1 Answers

"Overflow" means that the result of the adding of date components goes over the allowed range of that component. For example, adding 5 days to June 30 is an "overflow" because June 35 does not exist. Other examples include adding 7 hours to 18:00, 4 months to December, etc. This also applies to subtracting too.

What happens by default (wrapping components = false) is that the larger component gets incremented: if you add 5 days to June 30, you get July 5:

However, if you set it to true, it wraps around, meaning that the larger component doesn't change - you get June 5.

Today is June 8 for me. Adding 29 days with wrapping components gives June 7:

let newDate = Calendar.current.date(byAdding: DateComponents(day: 29), to: Date(), wrappingComponents: true)
print(newDate)
like image 57
Sweeper Avatar answered Sep 16 '26 06:09

Sweeper



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!