Home  >  Q&A  >  body text

How to check if a date is in the future, for separate date and time columns?

<p>I have two columns for storing dates: one is the date itself in YYYY-mm-dd format, and the other is the time in time(7) data type, e.g. 11:15:10.0000000. <br /><br />How do I check for future rows? <br /><br />I can get the first part, the date itself: </p><p><br /></p> <pre class="brush:php;toolbar:false;">MyModel::where('date', '>=', Carbon::today())->get()</pre> <p>But when I try to add the time, it doesn't work: </p> <pre class="brush:php;toolbar:false;">MyModel::where('date', '>=', Carbon::today())->where('time', '> ;', Carbon::now()->format('H:i'))->get()</pre> <p>Because they are separate, even if the date is in the future, the time is separate, so there may be a time mismatch. So I need to somehow merge the date and the time associated with it together, not separately. </p>
P粉021854777P粉021854777470 days ago532

reply all(1)I'll reply

  • P粉651109397

    P粉6511093972023-08-01 16:21:09

    Try to combine two columns into one condition.

    $now = Carbon::now();
    
    MyModel::whereRaw("CONCAT(`date`, ' ', `time`) >= ?", [$now->toDateTimeString()])->get();

    For SQL Server, try the following.

    MyModel::whereRaw("CONVERT(datetime, date + ' ' + CONVERT(varchar, time, 121)) >= ?", [$now->toDateTimeString()])->get();

    Query transformation may need updating, please consult the documentation for more information.

    reply
    0
  • Cancelreply