welid WG
welid WG

Reputation: 11

Laravel check current time is between two times

Well , i've tried every solution on the net conserning this problem but always the same result : false.

I'm trying to check exactly if current time is between 10 pm and 6 am at the same night , but all the solutions are returning false!!

For example , if i check between 8 am and 13 pm it works ! But only it's not working with the example i've given earlier. Any solutions guys ?

Edit : here is one of the examples i've tried

@php
$now = Carbon::now();
$start = Carbon::createFromTimeString("22:00 pm")
$end = Carbon::createFromTimeString("06:00 am");
@endphp


@if ($now->between($start, $end))
 //approved
@else
//not approved
@endif

Update: Problem solved finally , and here is the code for those who faced or will face this problem in the future :

@php
$now = Carbon::now();
$curr = date('a'); //return am or pm
$start = Carbon::createFromTimeString("22:00"); //init the start time
$end = Carbon::createFromTimeString("06:00"); //init the end time

if ($curr == 'am'){
$start = Carbon::createFromTimeString("22:00")->subDay();
//check if we are in the morning or after midnight , and go to yesterday datetime
}
else{
//then  we are in the evening or afternoon  , so add a day to get tomorrow's datetime
$end = Carbon::createFromTimeString("06:00)->addDay();
}
@endphp


@if ($now->between($start, $end,true))
 //approved
@else
//not approved
@endif

PS: im sure my code is not wrong i've been verifying it since days!

Upvotes: 0

Views: 1452

Answers (1)

welid WG
welid WG

Reputation: 11

The solution of the problem :

@php
$now = Carbon::now();
$curr = date('a'); //return am or pm
$start = Carbon::createFromTimeString("22:00"); //init the start time
$end = Carbon::createFromTimeString("06:00"); //init the end time

if ($curr == 'am'){
$start = Carbon::createFromTimeString("22:00")->subDay();
//check if we are in the morning or after midnight , and go to yesterday datetime
}
else{
//then  we are in the evening or afternoon  , so add a day to get tomorrow's datetime
$end = Carbon::createFromTimeString("06:00)->addDay();
}
@endphp


@if ($now->between($start, $end,true))
 //approved
@else
//not approved
@endif

Upvotes: 1

Related Questions