我正在使用Laravel,并使用Carbon::now()->addDay(1)
将列timeToEnd
字段设置为日期,这将给我接下来的24小时。但当我使用JavaScript从碳生成的日期开始计算一天、几小时和几秒时,它会给我17个小时。
这是我的代码:
$offer->timeToEnd = Carbon::now()->addDay(1);
if ($offer->save()) {
$isOk = true;
} else {
$isOk = false;
}
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let start = v["timeToEnd"], // <- It is the date generated by carbon.
countDown = new Date(start).getTime(),
interval = setInterval(function () {
let now = new Date().getTime(),
distance = countDown - now;
(document.getElementById(`days${v["id"]}`).innerText =
Math.floor(distance / day)),
(document.getElementById(
`hours${v["id"]}`
).innerText = Math.floor((distance % day) / hour)),
(document.getElementById(
`minutes${v["id"]}`
).innerText = Math.floor(
(distance % hour) / minute
)),
(document.getElementById(
`secounds${v["id"]}`
).innerText = Math.floor(
(distance % minute) / second
));
if (distance < 0) {
(document.getElementById(
`days${v["id"]}`
).innerText = 0),
(document.getElementById(
`hours${v["id"]}`
).innerText = 0),
(document.getElementById(
`minutes${v["id"]}`
).innerText = 0),
(document.getElementById(
`secounds${v["id"]}`
).innerText = 0);
$.ajax({
url: "/draw",
type: "POST",
data: {
id: v["id"],
_token: $('meta[name="csrf"]').attr(
"content"
),
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
},
});
clearInterval(interval);
}
//seconds
}, 1000);
})();
有人有解决方案吗?
尝试使用以下代码,
在控制器文件中
$time = Carbon::now()->addDay(1);
return view('time', compact('time'));
在正文标签关闭前的视图文件中,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
var time = '<?php echo $time ?>';
$(document).ready(function(){
countDown = new Date(time);
// console.log(countDown);
// now you can use your date variable countDown
});
</script>