Carbon create from timestamp
Asked Answered
T

2

5

I am trying to convert some dates

<p>{{  Carbon\Carbon::parse($post->created_at)->diffForHumans()  }}</p>

This works fine as the date is in the format 2017-05-01 10:52:51

However I also have the dates stored as unix timestamps.

How can I covert these to a date?

I already tried

{{  Carbon\Carbon::createFromTimestamp($post->created_at)->toDateTimeString()  }}

Error - A non well formed numeric value encountered

The dump is

 <pre class="xdebug-var-dump" dir="ltr">
<small>int</small> 
<font color="#4e9a06">1493637826</font>
    </pre>
Tamikotamil answered 1/5, 2017 at 11:8 Comment(8)
This is what I already tried Carbon\Carbon::createFromTimestamp($post->created_at)->toDateTimeString() }}Tamikotamil
No joy with that?Robison
Hi Robbie, no this is how I thought it would work and checked out the documentation before. It only seems to work with 1 or -1 as the argument.Tamikotamil
Can you share some example data from the $post->created_at value? (var_export)Robison
Added, it's an integer.Tamikotamil
Possible duplicate of Convert Unix Timestamp to Carbon ObjectRobison
I'll help you resolve this too because it doesn't seem to work for you...Robison
Ok, I've tried this with Carbon and it works as expected. I haven't used Laravel, but from what I can tell your syntax looks fine. Sorry. Try direct PHP echo instead of {{ }}Robison
D
8

Your first attempt using createFromTimestamp() is correct, so there must be something wrong with your input. Here is a working example:

>>> \Carbon\Carbon::createFromTimestamp(1493637826)->toDateTimeString();
=> "2017-05-01 11:23:46"

The error you encountered suggests you're passing in a DateTime string, not a unix timestamp:

>>> \Carbon\Carbon::createFromTimestamp('2017-05-01 11:23:46')->toDateTimeString();
PHP Notice:  A non well formed numeric value encountered
Dedra answered 18/10, 2018 at 15:24 Comment(0)
T
1

In the end I had to use gmdate to convert the timestamp.

{{  Carbon\Carbon::parse(gmdate("Y-m-d\TH:i:s", $post->date_posted))->diffForHumans()  }}

It is strange because it should work the way Robbie Averill suggested.

Tamikotamil answered 3/5, 2017 at 8:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.