DEV Community

Cover image for Time-Independent Dates in Swift
Hugh Jeremy
Hugh Jeremy

Posted on

Time-Independent Dates in Swift

Most often, it is important that a date also near-precisely represent a point in time. In Swift, for that, we have Foundation.Date. TimeIndependentDate fills a gap where, in limited circumstances, we need to deal with a date independent of time. This is particularly useful when interfacing with third party systems which supply dates independent of time.

I often find myself needing a time-independent date in Swift. So I've open-sourced a TimeIndependentDate type for anyone else that might need one: https://github.com/hwjeremy/time-independent-date-swift

Example Usage

// Initialise a date, throwing a `TimeIndependentDate` error if the supplied
// literal values are invalid.
let timeIndependentDate = try TimeIndependentDate(
    year: 2020,
    month: .january,
    day: 1
)

// Parse a date from a string. Adjust encoding order as desired. A
// `TimeIndependentDateError` is thrown if the supplied string
// is not a valid date.
let timeIndependentDate = try TimeIndependentDate.from(
    "2021-01-01",
    encodingOrder: .dayFirst
)

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay