如何在Laravel 5中获取Carbon的当前时间戳

问题描述 投票:23回答:6

我想在laravel 5获得当前的时间戳,我已经完成了 -

$current_time = Carbon\Carbon::now()->toDateTimeString();

我收到错误 - '未找到碳' -

enter image description here

我能做什么?

有人可以帮忙吗?

php laravel laravel-5 php-carbon
6个回答
69
投票

如果你想要日期时间字符串,你可以试试这个:

use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"

如果你想要时间戳,你可以尝试:

use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328

See the official Carbon documentation here


19
投票

对于Laravel 5.5或更高版本,只需使用内置帮助程序即可

$timestamp = now();

如果你想要一个unix时间戳,你也可以试试这个:

$unix_timestamp = now()->timestamp;

10
投票

您需要在碳类之前添加另一个\以在根命名空间中开始。

$current_time = \Carbon\Carbon::now()->toDateTimeString();

另外,确保在你的composer.json装载碳。


9
投票

Laravel 5.2 <= 5.5

    use Carbon\Carbon; // You need to import Carbon
    $current_time = Carbon::now()->toDayDateTimeString(); // Wed, May 17, 2017 10:42 PM
    $current_timestamp = Carbon::now()->timestamp; // Unix timestamp 1495062127

此外,这是如何在刀片中更改给定日期和时间的日期时间格式:

{{\Carbon\Carbon::parse($dateTime)->format('D, d M \'y, H:i')}}

Laravel 5.6 <

$current_timestamp = now()->timestamp;

2
投票

可能有点晚了,但您可以使用辅助函数time()来获取当前时间戳。我尝试了这个功能,它完成了工作,不需要课程:)。

您可以在https://laravel.com/docs/5.0/templates的官方文档中找到它

问候。


0
投票
date_default_timezone_set('Australia/Melbourne');   
$time = date("Y-m-d H:i:s", time()); 
© www.soinside.com 2019 - 2024. All rights reserved.