Search code examples
swiftfluentvaporvapor-fluent

Remove time from ISO date to filter with Vapor Swift


I'm trying to figure out how to filter ISO dates. I'd like to filter out Todo's for a specific day.

Dates are save in the database like this:

"started" -> 2022-03-17 18:46:44+00

I'd like to filter "started" like so

2022-03-17

Here's my query. I can't figure out a way to remove the time from the date.

func indexTodosByDate(req: Request) throws -> EventLoopFuture<[Todo]> {
    guard let dateFilter = req.parameters.get("date", as: Date.self) else {
        throw Abort(.badRequest)
    }   
    return Todo.query(on: req.db)
        .filter(\.$started == dateFilter)
        .with(\.$user)
        .all()
}

Solution

  • Whilst @0xTim has identified the correct method, I hope this will give you the necessary code to achieve what you want.

    First, extend Date to give you midnight on the date in question:

    extension Date {
        var midnight: Date { return Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: self)! }
    }
    

    Then, use this in a query's filter:

    let query = ToDo(on: database).filter(\.$started >= dateFilter.midnight)