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!

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
yu xia
  • 397
  • 2
  • 14

1 Answers1

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()])
Robin Schambach
  • 19,713
  • 1
  • 19
  • 44
  • 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 01 '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 https://github.com/craftcms/cms/blob/develop/src/web/twig/variables/CraftVariable.php#L262 – Robin Schambach May 01 '18 at 14:02