4

I'm using Craft 3 and I would like to do the following thing:

There is a start date and an end date filed in entry, is it possible to get entries that are between these two dates in PHP?

Thank you!

4
Entry::find()->startDate('>='. $someTime).endTime('<='.$someOtherTime).all();

Those variables can be timestamps, DateTimes or a correctly formated time string.

Here are some variants of these filters

Entry::find()
    ->variantOne('<=' .  Db::prepareDateForDb(new \DateTime())) <-- DateTime object
    ->variantTwo('<=' . time())  <-- as timestamp
    ->variantThree('<=' . (new \DateTime())->format('U')) <-- timestamp as well
    ->variant(['and', '<=' . time() , '>=' . time() - 3600]) <-- entries within the last hour
    ->validString(['or', '>=' . (new DateTime())->format('Y-m-d H:i:s'), '<= ' . time()])
| improve this answer | |
  • I tried $entites = Entry::find()->startDate('>='. (new \DateTime('now'))->format('m/d/Y') )->all();, but got an database error like SQLSTATE[22007]: Invalid datetime format: 7 ERROR: invalid input syntax for type timestamp: "" – yu xia Apr 19 '18 at 22:26
  • @yuxia I've added a few examples – Robin Schambach Apr 19 '18 at 22:49
  • Works just like magic!!! Many many thanks:) – yu xia Apr 19 '18 at 23:02
  • I had the same problem the other day and solved it like this {% set params = { section : 'theSection', startDate : '>=' ~ someTime, endDate : '<=' ~ someOtherTime, } %} {% set entries = craft.entries(params).all() %} Are there benefits to Entry::find() over craft.entries(params)? – Johann Dyck May 1 '18 at 14:00
  • 1
    @JohannDyck Entry::find is PHP Syntax, craft.entries is twig syntax that executes Entry::find() You can see what craft.entries does here github.com/craftcms/cms/blob/develop/src/web/twig/variables/… – Robin Schambach May 1 '18 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.