繁体   English   中英

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

[英]How to get Current Timestamp from Carbon in Laravel 5

我想在 laravel 5 中获取当前时间戳,我已经做到了-

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

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

在此处输入图片说明

我能做什么?

请问有人可以帮忙吗?

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

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

请参阅此处的官方 Carbon 文档

对于 Laravel 5.5 或更高版本,只需使用内置助手

$timestamp = now();

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

$unix_timestamp = now()->timestamp;

您需要在您的 carbon 类之前添加另一个\\以在根命名空间中启动。

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

另外,请确保 Carbon 已加载到您的composer.json

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;

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

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

问候。

在 Class 声明之前使用\\调用根命名空间:

$now = \Carbon\Carbon::now()->timestamp;

否则,它会在类开头声明的当前命名空间中查找它。 其他解决方案是使用它:

use Carbon\Carbon
$now = Carbon::now()->timestamp;

你甚至可以给它一个别名:

use Carbon\Carbon as Time;
$now = Time::now()->timestamp;

希望能帮助到你。

date_default_timezone_set('Australia/Melbourne');   
$time = date("Y-m-d H:i:s", time()); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM