碳日期时间不同
Carbon date time differs
案例
使用 Middleware
、Session
和 Carbon
检查 session/shopping cart
是否已创建 longer than 20 minutes ago
,以便可以刷新会话。 (路由在中间件内分组)
Current data is being run on Homestead, but same problems occur on my live website which is being run on a Digital Ocean server
class CheckCart
{
public function handle($request, Closure $next)
{
// Defining current timestamp
$now = Carbon::now();
// created_at from the session
$created_at = $request->session()->get('created_at');
// If the cart count is == 1, & created_at is null -> put created at date in session
if (Cart::count() == 1 && $created_at == null) {
$request->session()->put('created_at', $now);
}
// If created at date + 20 minutes is earlier than current time, flush (empty) session
if ($created_at != null) {
if ($created_at->addMinutes(20) < $now) {
$request->session()->flush();
}
}
return $next($request);
}
}
问题
Local time
来自我的 Macbook 是 2017-01-06 00:00
Carbon::now()
是 2017-01-05 23:25
created_at
时间戳(最终由 Carbon::now()
设置)是 2017-01-06 03:20
这些时间戳怎么会相差这么多,尤其是 Carbon::now()
定义的 created_at
在某个时间点怎么会至少晚 7 小时?
- 所有时区都是
Europe/Amsterdam
问题出在 $created_at->addMinutes(20)
。每次执行您的代码(通过刷新、请求或其他方式)时,会话值都会增加 20 分钟。然后还有评论中提到的Homestead时间与您的实际机器不同的问题。
要解决 created_at
问题,您应该通过执行 $created_at->copy()->addMinutes(20)
来复制它。在实际需要副本而不是对象本身的所有其他代码中应用此技巧。希望对您有所帮助!
案例
使用 Middleware
、Session
和 Carbon
检查 session/shopping cart
是否已创建 longer than 20 minutes ago
,以便可以刷新会话。 (路由在中间件内分组)
Current data is being run on Homestead, but same problems occur on my live website which is being run on a Digital Ocean server
class CheckCart
{
public function handle($request, Closure $next)
{
// Defining current timestamp
$now = Carbon::now();
// created_at from the session
$created_at = $request->session()->get('created_at');
// If the cart count is == 1, & created_at is null -> put created at date in session
if (Cart::count() == 1 && $created_at == null) {
$request->session()->put('created_at', $now);
}
// If created at date + 20 minutes is earlier than current time, flush (empty) session
if ($created_at != null) {
if ($created_at->addMinutes(20) < $now) {
$request->session()->flush();
}
}
return $next($request);
}
}
问题
Local time
来自我的 Macbook 是2017-01-06 00:00
Carbon::now()
是2017-01-05 23:25
created_at
时间戳(最终由Carbon::now()
设置)是2017-01-06 03:20
这些时间戳怎么会相差这么多,尤其是 Carbon::now()
定义的 created_at
在某个时间点怎么会至少晚 7 小时?
- 所有时区都是
Europe/Amsterdam
问题出在 $created_at->addMinutes(20)
。每次执行您的代码(通过刷新、请求或其他方式)时,会话值都会增加 20 分钟。然后还有评论中提到的Homestead时间与您的实际机器不同的问题。
要解决 created_at
问题,您应该通过执行 $created_at->copy()->addMinutes(20)
来复制它。在实际需要副本而不是对象本身的所有其他代码中应用此技巧。希望对您有所帮助!