davedelong / time

Robust and type-safe date and time calculations for Swift
MIT License
2.32k stars 77 forks source link

Getting a Foundation `Date` from `Value` #36

Closed jdmcd closed 4 years ago

jdmcd commented 4 years ago

Hey there,

Thank you for this fantastic library!! Quick question that I couldn't find in the docs (hopefully I didn't just miss it).

I need to calculate a date 5 minutes from now in UTC. Here's what I'm doing:

let utc = Clock.system.converting(to: TimeZone(identifier: "UTC")!).thisMinute()
let plusFiveMinutes = (utc + .minutes(5)).firstInstant.date

I'm clear on everything up until .firstInstant.date - that was the only way I could find to pull a Foundation Date out of my addition operation. Does that seem right?

Thank you again!

davedelong commented 4 years ago

Yep, this is probably correct for what you're trying to do.

All calendar values represents ranges of possible instants. When you're asking for "5 minutes from now", you're getting back a value that contains all possible Instants in that 5-minute range.

Technically, any Instant value within that range meets the criteria of "occurs five minutes from now", because your accuracy is only down to the minute (because you used .thisMinute()).

The firstInstant of an absolute Value is therefore the first point in time that meets the criteria of being "five minutes from now".

And then once you've got an Instant, you can easily convert it back to a Foundation.Date by using its .date value.


All this to say that yes, this is correct. 😁

jdmcd commented 4 years ago

@davedelong thanks so much for the quick response! This actually helps tighten my understanding quite a bit, I think I was missing the key point about values being ranges, not singular points. Thank you!!

ricobeck commented 4 years ago

Thanks! That helped me a lot.

Did I miss this in the documentation? If not I'd suggest that it should be mentioned somewhere explicitly because after reading in the docs I was under the impression that converting back to Foundation.Date is impossible.