Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carbon now time wrong

I just started using the Carbon extension (seems pretty sweet so far), but am confused on the Carbon::now() function. According to the docs, it seems as though this function should reflect the current time in the users current timezone, however, I seem to get a time that is an hour ahead of GMT.

i.e. Carbon::now() says 2015-01-01 17:26:46 when I am on PST and it is actually currently 2015-01-01 08:26:46.

Do I have to detect and put in a users local timezone for all instances?

What gives? (I very well may have a fundamental misunderstanding of how a website gets a users local time)

like image 949
ambe5960 Avatar asked Jan 01 '15 16:01

ambe5960


People also ask

How do you find the current date using carbon?

Carbon today php require __DIR__ . '/vendor/autoload. php'; use Carbon\Carbon; $now = Carbon::now(); echo "$now\n"; $today = Carbon::today(); echo "$today\n"; Carbon::now returns the current date and time and Carbon:today returns the current date.

How does carbon change time zones?

First, you set the timezone you initially have, so if you store your date in the database as UTC, then set the default timezone to UTC, then use ->setTimeZone('Valid/Timezone') to make the change from what you'v had to the new timezone.

How does carbon add time?

You can add hours on current date using carbon in laravel 6, laravel 7, laravel 8 and laravel 9 version. If you need to add hour or more hours in date then you can use carbon in laravel. carbon provide addHour() and addHours() method to add hours on carbon date object.


2 Answers

Carbon is UTC based therefore simply doing Carbon::now() will output the time in UTC format

You have to specify the timezone for an accurate reflection of the dateTime in your city or area.

There are two ways to do this. You can either do:

Carbon::now('PST') OR Carbon::now('Continent/City') like (Carbon::now('America/Montreal') for example

like image 102
Frank L Avatar answered Sep 19 '22 03:09

Frank L


This appears to be because the timezone of your server is different to your own.

This could be caused by:

  • Server misconfiguration
  • Physical location of the server is in a different timezone
  • Policies of your provider could also cause this. If your provider decides they want to operate on the same timezone on every server they have throughout the world, this will cause issues.

The server's timezone appears to be CET (Central European Time) which is +1 GMT, as you described.

To fix this, you should change the timezone in your php.ini file (instructions are from the link):

  1. Open your php.ini file
  2. Add the following line of code to top of your php.ini file:

date.timezone = "US/Central"

Alternatively you should replace the US/Central timezone with the desired timezone as outlined here if you wish PHP to use another timezone.

like image 42
AStopher Avatar answered Sep 21 '22 03:09

AStopher