11

I have a datetime string of format 'Y-m-d H:i:s', and datetime value as '2018-01-30 07:11:21'.

$carbon_obj = Carbon::createFromFormat('Y-m-d H:i:s' , '2018-01-30 07:11:21','America/Chicago');

How do it get the Unix timestamp from this carbon object?

Dinesh Gowda
  • 1,044
  • 3
  • 13
  • 29

2 Answers2

23

just add timestamp at the back of your code.

$carbon_obj = Carbon::createFromFormat('Y-m-d H:i:s' , '2018-01-30 07:11:21','America/Chicago')->timestamp;

or

$carbon_obj = Carbon::createFromFormat('Y-m-d H:i:s' , '2018-01-30 07:11:21','America/Chicago');
$carbon_obj->timestamp;

If you have data missing error. missing it is the data your passed it not a complete date format.

Try this.

$timestp = Carbon::createFromFormat('Y-m-d H:i:s', Carbon::parse($trans['transaction_datetime']) ,Setting::get('timezone'))->timestamp;
myselfmiqdad
  • 2,518
  • 2
  • 18
  • 33
Shiro
  • 7,344
  • 8
  • 46
  • 80
  • tried that but it says error **Exception with message Data missing** – Dinesh Gowda Jan 30 '18 at 09:55
  • The code is tested in `php artisan tinker`. You should able to get the result too. I suspect there is another part of your code break it. Try run your `php artisan tinker` – Shiro Jan 30 '18 at 12:22
  • Yes i tried in tinker it works. In Code also in doing the same thing but it says data missing. Below is the code which is being used – Dinesh Gowda Jan 30 '18 at 12:35
  • `$timestp = Carbon::createFromFormat('Y-m-d H:i:s' ,$trans['transaction_datetime'] ,Setting::get('timezone'))->timestamp;` – Dinesh Gowda Jan 30 '18 at 12:35
  • can you show me your `$trans['transaction_datetime'] ` output? I updated my answer, you add `Carbon::parse()` inside your date data. It should be worked. – Shiro Jan 30 '18 at 14:08
0

You can use Carbon::shiftTimezone to change the timezone without changing the dates and time.

$dt = Carbon::parse('2020-03-27');
dump($dt);   //2020-03-27 00:00:00.0 Asia/Kolkata (+05:30)
dump($dt->shiftTimezone('utc'));  //2020-03-27 00:00:00.0 UTC (+00:00)
N Kumar
  • 1,302
  • 1
  • 18
  • 25