Home > Back-end >  Remove time from ISO date to filter with Vapor Swift
Remove time from ISO date to filter with Vapor Swift

Time:03-27

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()
}

CodePudding user response:

If you're using the standard date formats and it's using a datetime as the field type in your migration, you can't.

What you need to do is write a query that searches for date is greater than or equal to the day at 00:00 and less than or equal to 23:59 etc. Do work out the start of the day and end of the day and pass that to your filters. Swift's Calendar APIs have functions to get the start of a day

CodePudding user response:

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)
  • Related