如果你想要日期时间字符串,可以尝试这个:
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
对于 Laravel 5.5 或以上版本,只需使用内置的帮助程序即可。
$timestamp = now();
如果你想要一个Unix时间戳,你也可以尝试这样做:
$unix_timestamp = now()->timestamp;
您需要在您的 carbon 类之前再添加一个 \
,以便在根命名空间中启动。
$current_time = \Carbon\Carbon::now()->toDateTimeString();
另外,请确保在您的 composer.json
文件中加载了 Carbon。
composer.json
文件中。但是,如果您想确保它已安装,请在应用程序根目录的控制台中键入composer require nesbot/carbon
进行安装。 - JerodevLaravel 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
此外,以下是如何在blade中更改给定日期和时间的datetime格式:
{{\Carbon\Carbon::parse($dateTime)->format('D, d M \'y, H:i')}}
Laravel 5.6以下版本
$current_timestamp = now()->timestamp;
在类声明前加一个\
,你就是在调用根命名空间:
$now = \Carbon\Carbon::now()->timestamp;
use Carbon\Carbon
$now = Carbon::now()->timestamp;
你甚至可以给它分配一个别名:
use Carbon\Carbon as Time;
$now = Time::now()->timestamp;
使用 Carbon 生成时间戳的最佳方式如下:
use Carbon\Carbon
$now = Carbon::now()->getTimestamp(); // timestamp (seconds)
$now = Carbon::now()->getTimestampMs(); // timestamp (milliseconds)
适用于 Laravel 5、6、7、8、9 和 10(截至撰写本文时的最新版本)。流畅易读,您不需要记住所有的 PHP 日期格式。
date_default_timezone_set('Australia/Melbourne');
$time = date("Y-m-d H:i:s", time());
now()
将以典型的2018-10-05 17:55:08
格式返回。 - Ryan DuValnow()
实际上返回一个 Carbon 对象。如果你在 Blade 模板中输出它,它会被渲染成字符串,但它本质上是一个完整的、复杂的对象。 - ceejayoz