An easier way to create dates in Swift

TL;DR? I’ve open sourced DateBuilder, a powerful date calculation library. Check out the README to see all the incredible stuff it can do.

Apple’s Calendar API is amazing, it is. It’s quite obscure in some parts, true, and it requires quite a little bit of learning and adjusting, but it’s very effective, very expansive, and, most of all, very correct. If you do everything right, it works great and it handles all the weird edge cases for you.

But still, when you need to create very specific dates it can get a little tricky. Expressing even something as simple as “tomorrow at 8pm” requires you to know exactly what you’re doing, and calculating something like “first day of next week” will send you down a 30-minute Google road exploring billions of different solutions, most of which are wrong (because yes, believe it or not, there are places in the world where the week doesn’t start on Sunday).

Introducing DateBuilder

To make the power of Calendar and date calculations available to everyone, I’ve now open sourced DateBuilder. It’s a powerful date creation engine that lets you create Date and DateComponents objects with incredible ease using a very visual, declarative syntax.

I built this while working on my upcoming local notification library. For the scheduling component I wanted something very expressive, very concise and easy-to-understand.

For example, at one point I needed to schedule a notification for every first day of the week, with a sort of “weekly review”. With DateBuilder, it’s incredibly easy:

EveryWeek(forWeeks: 50, starting: .thisWeek)
.firstDay
.at(hour: 10, minute: 00)
.dateComponents() // [DateComponents]

One can then use this array of DateComponents to schedule a bunch of notifications, easy as that.

I won’t go into much detail about the API in this post, because there’s a whole README on GitHub! Just take a brief look to see all the stuff DateBuilder can do.

I’m very excited about launching this new open source package, and excited to hear your thoughts and opinions on it! I’m sure it’ll be quite useful for many many apps out there.

Please try it out and let me know how it goes! Do you find it useful? Is there anything that you’re missing? Do you want it to have any other features, or to have even more flexibility? Use the comments section below, open a GitHub issue or drop me a line at oleg@dreyman.dev, I’ll be happy to help!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Oleg Dreyman

Oleg Dreyman

797 Followers

iOS development know-it-all. Talk to me about Swift, coffee, photography & motorsports.