Carbon changing timezone of parsed datetime string automatically

27 views Asked by At

I am trying to simply parse a datetime string like "2024-3-3 16:00" and do some other calculations like addHour and do some conditions. The problem is that when I try to parse 2024-3-3 16:00 and return it, it returns 2024-3-3 14:00. I don't understand how is that possible. the timezone in my config/app.php is set to Africa/Cairo. what I understand is that it takes this datetime in UTC and converts it to the configuration timezone. Even if I explicitly gave it a timezone like Carbon::parse('2024-3-3 16:00', 'Europe/London'), it also returns the same thing. Can someone please explain what is happening?

Edit This code was in the routes folder in user.php, I created a route for testing called /run. I tried using Carbon::parse(...) in blade, it worked fine.

class TestController extends Controller
{
    public function index() {
        return Carbon::parse('2024-3-3 16:00');
    }
}

output:

"2024-03-03T14:00:00.000000Z"

1

There are 1 answers

0
Div_OR On

The answer was very simple I feel dumb. I just had to enter the datetime in UTC

Carbon::parse('2024-3-3 16:00', 'UTC')