Reputation: 31
I have a timestamp in my database:
2017-10-01 04:32:37
Now, I need to grab only the date, so like "01/10"
I'm trying to do this with Laravel's Carbon library, can anyone tell me how? I can't find anything to do with this in the documentation, it seems unheard of?
I want to do this with Carbon
Upvotes: 3
Views: 1949
Reputation: 149
field created_at
and updated_at
returned as Carbon object, you can directly format that attributes like this
$user = App\User::find(1);
// created at value
// 2017-12-20 06:30:25
$user->created_at->format('d/m');
// will return
// 20/12
or if you have custom date attributes you can use Carbon::parse()
methods like this
$approvedAt = '2017-10-02 05:30:00';
$initDate = Carbon::parse($approvedAt);
$approvedAtFormated = $initDate->format('d/m');
// will return
// 02/10
Upvotes: 1
Reputation: 16817
As described in the "String Formatting" section of the Carbon docs, we can use the format()
method to produce any format that PHP understands:
Carbon::parse('2017-10-01 04:32:37')->format('d/m');
// "01/10"
Carbon supports the same format notations as PHP's strtotime()
function and DateTime
class.
Laravel automatically converts any Eloquent model attributes declared in a model's $dates
or $casts
arrays to Carbon instances. This lets us use Carbon-specific functionality without the need to manually parse the date into Carbon:
$user->created_at->format('d/m');
$user->last_login->format('d/m');
Upvotes: 0
Reputation: 8078
you can use format
$re= Carbon::createFromFormat('Y-m-d H:i:s','2017-10-01 04:32:37')->format('d/m');
dd($re);
output
"01/10"
Also you can use
$updated_at=Carbon::parse( '2017-10-01 04:32:37')->format('d/m');;
dd($updated_at);
output
"01/10"
If you are converting updated_at
and created_at then you directly format datetime using carbon
for example
$blogTag=Tag::retrieveTagById(1);
dd($blogTag->created_at->format('d/m'));
Output will be
"01/10"
Upvotes: 0
Reputation: 3630
Its been a long time since I used PHP and Laravel so I may be wrong.
But you can use $carbon->format("format string")
to make any string you want out of your carbon instances
My guess you can do something like:
Carbon::now()->format("d/m");
Upvotes: 1