Laravel ORM, date compare

后端 未结 6 1393
情歌与酒
情歌与酒 2021-02-03 23:41

I\'m using Laravel Framework.

I want all of the rows for this day. This is what I tried:

DB::table(\'users\')->where(\'created_at\', \'>=\', date(         


        
相关标签:
6条回答
  • 2021-02-04 00:01

    Simply:

    DB::table('users')->where('created_at', '>=', date('Y-m-d'). ' 00:00:00')
    

    When getting all rows for this day(the time should be 00:00:00), so make sure to set the date condition to current date plus 00:00:00 i.e.

    date('Y-m-d'). ' 00:00:00'
    
    0 讨论(0)
  • 2021-02-04 00:01

    Use whereDate

    $users = DB::table('users')
                    ->whereDate('created_at', '2016-12-31')
                    ->get();
    

    other functions you may use are: whereDate / whereMonth / whereDay / whereYear / whereTime

    0 讨论(0)
  • 2021-02-04 00:05

    I know that topic is old but may someone try to find a solution from search engines.

    You can use:

    User::whereDate('created_at', '=', Carbon::today()->toDateString());
    

    You can visit this link if you want to know more about date comparison in Laravel using where.

    Eloquent date filtering: whereDate() and other methods

    0 讨论(0)
  • 2021-02-04 00:10

    date('Y-m-d H:i:s') returns date of now.

    If you want results from start of the day you can replace it with date('Y-m-d').' 00:00:00'.

    If you want results from last 24 hours you can replace it with date('Y-m-d H:i:s',time()-86400) (86400 = 24*60*60)

    0 讨论(0)
  • 2021-02-04 00:16

    For those who only need to compare a date without time, Lavarel provided a handy function whereDate:

    User::whereDate('created_at', '>=', date('Y-m-d'));
    

    http://laraveldaily.com/eloquent-date-filtering-wheredate-and-other-methods/

    0 讨论(0)
  • 2021-02-04 00:18

    Hmmm...there was a good answer to this question which seems to have now disappeared.*

    It was something like this:

    User::where('created_at', '>=', new DateTime('today'))
    

    Note: if you're putting this code in a file with a namespace, or might use a namespace in the future, you should prefix the DateTime class with a backslash: new \DateTime('today').

    * https://stackoverflow.com/questions/15052679/laravel-framework-how-to-get-today-queries

    0 讨论(0)
提交回复
热议问题