Shanka SMS
Shanka SMS

Reputation: 654

Laravel 5 generation carbon date time with timezone

I have publish ERP site in cloud platform and I want to generate datetime for user assigned timezones.

I am using carbon datetime library to convert. But its gave me bellow issue when i am converting.

$carbon = new Carbon();
$carbon->setTimezone('Asia/colombo');
echo $carbon;           //output is  : 2016-07-06 22:33:05 | Asia/colombo
BUT
echo $carbon->now()     // output is : 2016-07-06 17:03:05 | UTC

Why $carbon->now is giving wrong timezone even I have set timezone in carbon object also....

sorry If I am thinking wrong way.........

Upvotes: 2

Views: 4465

Answers (2)

shock_gone_wild
shock_gone_wild

Reputation: 6740

If you use Carbon's setTimezone() function on an object, you should only call non static functions on that object.

After manually applying a timezone, just use the non static output functions.

Some examples:

// without parameters it is now() !
$carbon = new Carbon\Carbon();
$carbon->setTimezone('Asia/colombo');
echo $carbon->toDateTimeString()."<br>";
// custom output format
echo $carbon->format('d.m.Y H:i:s')."<br>";

$carbon->setTimezone('Europe/Berlin');
echo $carbon->toDateTimeString()."<br>";
// custom output format
echo $carbon->format('d.m.Y H:i:s')."<br>";


// or pass something compatible to http://php.net/manual/en/datetime.construct.php
$carbon = new Carbon\Carbon('24.12.2015 20:13');
$carbon->setTimezone('Asia/colombo');
echo $carbon->toDateTimeString()."<br>";
// custom output format
echo $carbon->format('d.m.Y H:i:s')."<br>";

$carbon->setTimezone('Europe/Berlin');
echo $carbon->toDateTimeString()."<br>";
// custom output format
echo $carbon->format('d.m.Y H:i:s')."<br>";

The static methods will use the timezone defined in your config/app.php ( default: UTC)

Upvotes: 1

The Maniac
The Maniac

Reputation: 2626

Carbon::now is a static function, which you invoke on your object but it is still a static function. There is no underlying object to pull the timezone information from. You need to do this: Carbon::now('Asia/colombo')

Upvotes: 3

Related Questions