Laravel Carbon 秒到 forHumans

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33645372/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:40:26  来源:igfitidea点击:

Laravel Carbon seconds to forHumans

phplaravellaravel-5

提问by Froxz

I have a table with column seconds, where I insert online time (in seconds),

我有一个列秒表,我在其中插入在线时间(以秒为单位),

Carbon::parse($seconds)->forHumans();

Doesnt allow me to do this, there is a way to parse seconds and transfer it to humans reading? like 1 hour or 2 weeks?

不允许我这样做,有没有办法解析秒并将其传输给人类阅读?像 1 小时还是 2 周?

回答by Maltronic

This should return the result you're after:

这应该返回您所追求的结果:

Carbon::now()->subSeconds($seconds)->diffForHumans();

回答by ArtisanBay

Try this:

尝试这个:

Carbon Time in Human readable format

人类可读格式的碳时间

// $sec will be the value from your seconds table
echo Carbon::now()->addSeconds($sec)->diffForHumans();
// OR
echo Carbon::now()->subSeconds($sec)->diffForHumans();

Output

输出

// if $sec = 5
5 seconds from now

Found this useful doc Carbon

找到了这个有用的文档Carbon

Hope this is helpful.

希望这是有帮助的。

回答by Abdelhakim Ezzahraoui

1) php artisan make:middleware LastActivityUser

1) php artisan make:middleware LastActivityUser

2) Add this code in middleware LastActivityUser

2)在中间件LastActivityUser中添加这段代码

 <?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Carbon\Carbon;
use Cache;

class LastActivityUser
 {
     /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
     protected $auth;

     /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
     public function __construct(Auth $auth)
     {
         $this->auth = $auth;
     }
     /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check()) {
            $expiresAt = Carbon::now()->addSeconds(10);
            Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
        }
        return $next($request);
    }
}

3) Add This Function in Your User Model

3) 在您的用户模型中添加此功能

public function is_online() {
        return Cache::has('user-is-online-' . $this->id);
    }

4) Declare in (app\Http\Kernel.php)

4) 在 (app\Http\Kernel.php) 中声明

protected $middlewareGroups = [
   'web' => [

       \App\Http\Middleware\LastActivityUser::class, //Add this Line
   ]

5) in Your Template Blade

5)在你的模板刀片中

 @if($user->is_online())
   <span>On</span>
 @else 
   <span>Off</span>
 @endif