Convert Unix Timestamp to Carbon Object
Asked Answered
F

3

109

I have unix timestamp in table, wants to show to user using Carbon. How can I achieve ?

e.g.

1487663764.99256
To
2017-02-24 23:23:14.654621
Frausto answered 28/2, 2017 at 14:8 Comment(0)
G
233

Did you check the carbon docs? I think this is what youre looking for:

Carbon::createFromTimestamp(-1)->toDateTimeString(); 

Checkout http://carbon.nesbot.com/docs/#api-instantiation

Godship answered 28/2, 2017 at 14:13 Comment(5)
I sometimes forget the method name myself sometimes so when i google search "Carbon from unix timestap" and come across this post, im like heck yeah thumbs up for this guy and i get "you cant vote for your own post" lol :DGodship
@Godship LOL that moment when you realiseUngracious
Actually Carbon::parse() does the sameUnhitch
LOL. Thanks for this answer. I may have came across this answer several times.. :-DGloze
@miken32 aha you are right I just confirmed.Mhd
P
33

There are several ways to create Carbon instances described in the Carbon documentation, which is linked at the bottom of the project's README. The relevant section is this:

The final two create functions are for working with unix timestamps. The first will create a Carbon instance equal to the given timestamp and will set the timezone as well or default it to the current timezone. The second, createFromTimestampUTC(), is different in that the timezone will remain UTC (GMT). The second acts the same as Carbon::createFromFormat('@'.$timestamp) but I have just made it a little more explicit. Negative timestamps are also allowed.

So you can just do:

$carbon = Carbon::createFromTimestamp($dbResult['SomeTimestampColumn']);
Pregnancy answered 28/2, 2017 at 14:12 Comment(1)
SO is better than docs. An idea could be to convert docs to SO format :)Valenti
P
5

If you really love your fluid method calls and get frustrated by the extra line or ugly pair of brackets necessary when using the constructor you'll enjoy the parse method:

Carbon::parse(1487663764);
Carbon::parse('first day of next month');
Pairoar answered 18/11, 2021 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.