Laravel/Carbon将两个时间戳加在一起? [英] Laravel / Carbon adding two timestamps together?
问题描述
我正在开发一个系统,人们可以在该系统上启动和停止某项操作,该操作可以计算花费了他们的时间.这是通过以下方式完成的:
I am working on a system where people can start and stop something which calculates the time it has taken them. This is done by:
-
当按下开始"按钮时,该行的日期将添加到数据库表中.
When the "Start" button is pressed, a date is added into the database table for that row.
当按下停止"按钮时,添加了一个日期(结束日期),然后我通过以下方式计算差异:
When the "Stop" button is pressed, a date (end date)is added then I calculate the difference by:
$startTime = \Carbon\Carbon::parse($task->date_start);
$finishTime = \Carbon\Carbon::parse($task->date_complete);
$totalDuration = $finishTime->diffInSeconds($startTime);
"timeSpent" $totalDuration
也存储为时间戳.
And also "timeSpent" $totalDuration
is stored as a timestamp.
需求已更改,以便用户可以停止/启动,但仍保留总时间.我的想法是:
The requirements have changed so that the user can stop/start but it still holds the the total time. My idea is:
通过与下面相同的过程,始终存储timeSpent
,因此,如果用户再次单击开始/停止",我可以像以前一样计算出差异,然后将其添加到存储在内部的timeSpent
中.数据库,但是我似乎无法弄清楚该如何做.我已经尝试过:
With the same process as below, the timeSpent
is always stored, so if a user clicks start/stop again I can just calculate the difference as done previously and then add it to the timeSpent
that is stored inside the database, however I can't seem to figure out how to do this. I have tried:
$totalTimeSpent = strtotime($task->time_spent) +
strtotime($totalDuration);
然后再次解析它:
$total = \Carbon\Carbon::parse($totalTimeSpent);
但这会导致错误:
无法解析位置7(0)处的时间字符串(1463184003):意外字符
Failed to parse time string (1463184003) at position 7 (0): Unexpected character
有人可以建议替代方法吗?
Can someone suggest an alternative?
推荐答案
您不应将 $ totalDuration 存储在类型为 timestamp 的字段中,因为它不是时间戳.只有几秒钟,应该存储在一个整数字段中.
You shouldn't store $totalDuration in a field with type timestamp because it's not a timestamp. It's just a number of seconds and should be stored in an integer field.
一旦使用整数类型,添加数字就不会有任何问题:
Once you use integer type for that, you shouldn't have any issues with adding the numbers:
$total = $task->time_spent + $totalDuration;
这篇关于Laravel/Carbon将两个时间戳加在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!