php 如何在 Laravel 5 中从 Carbon 获取当前时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32719972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Current Timestamp from Carbon in Laravel 5
提问by Abrar Jahin
回答by Md Rashedul Hoque Bhuiyan
You can try this if you want date time string:
如果你想要日期时间字符串,你可以试试这个:
use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"
If you want timestamp, you can try:
如果你想要时间戳,你可以尝试:
use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328
回答by Him Hah
For Laravel 5.5 or above just use the built in helper
对于 Laravel 5.5 或更高版本,只需使用内置助手
$timestamp = now();
If you want a unix timestamp, you can also try this:
如果你想要一个unix时间戳,你也可以试试这个:
$unix_timestamp = now()->timestamp;
回答by Jerodev
You need to add another \
before your carbon class to start in the root namespace.
您需要\
在您的 carbon 类之前添加另一个以在根命名空间中启动。
$current_time = \Carbon\Carbon::now()->toDateTimeString();
Also, make sure Carbon is loaded in your composer.json
.
另外,请确保 Carbon 已加载到您的composer.json
.
回答by Sadee
Laravel 5.2 <= 5.5
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
In addition, this is how to change datetime format for given date & time, in blade:
此外,这是如何在刀片中更改给定日期和时间的日期时间格式:
{{\Carbon\Carbon::parse($dateTime)->format('D, d M \'y, H:i')}}
Laravel 5.6 <
Laravel 5.6 <
$current_timestamp = now()->timestamp;
回答by Brayhan E. Contreras Reyes
It may be a little late, but you could use the helper function time()to get the current timestamp. I tried this function and it did the job, no need for classes :).
可能有点晚了,但您可以使用辅助函数time()来获取当前时间戳。我试过这个功能,它完成了工作,不需要类:)。
You can find this in the official documentation at https://laravel.com/docs/5.0/templates
您可以在https://laravel.com/docs/5.0/templates的官方文档中找到它
Regards.
问候。
回答by Tereh Sumasino
date_default_timezone_set('Australia/Melbourne');
$time = date("Y-m-d H:i:s", time());
回答by Marcos Di Paolo
With a \
before a Class declaration you are calling the root namespace:
在\
Class 声明之前,您正在调用根命名空间:
$now = \Carbon\Carbon::now()->timestamp;
otherwise it looks for it at the current namespace declared at the beginning of the class. other solution is to use it:
否则,它会在类开头声明的当前命名空间中查找它。其他解决方案是使用它:
use Carbon\Carbon
$now = Carbon::now()->timestamp;
you can even assign it an alias:
你甚至可以给它一个别名:
use Carbon\Carbon as Time;
$now = Time::now()->timestamp;
hope it helps.
希望能帮助到你。