时区差异导致使用Laravel和javascript时剩余的时间不正确

问题描述 投票:0回答:1

我正在尝试在预订页面中获取剩余时间。我给javascript预定的日期和确切开始时间如下:

if (Auth()->user()->role == 1) { //this is the owner of the time slot that was selected. So it makes sense not to set a time zone for him.
    $dateTime = Carbon::parse($dateTime . ' ' . $book->from);
} else { //this is a normal user
    $dateTime = Carbon::parse($dateTime . ' ' . $book->from)->setTimezone(Auth()->user()->time_zone);
}

并且javascript函数按如下方式处理它:

<script>
$(document).ready(function() {
    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1)
    $('.date').datepicker({minDate: tomorrow, dateFormat: 'yy-mm-dd'});

    currentDate = new Date();
    currentDateNextFiveDays =  currentDate;
    remainingTime =  new Date(currentDateNextFiveDays) - new Date(currentDate);
    // Set the date we're counting down to
    var countDownDate = new Date("{{$dateTime}}");
    // Update the count down every 1 second
    var x = setInterval(function() {
        // Get today's date and time
        var now = new Date().getTime();
        // Find the distance between now and the count down date
        var distance = countDownDate - now;
        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        // days = days * 24;
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        // hours = hours + days;
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
        // Display the result in the element with id="demo"
        if(-3000 < distance && distance < -1000) {
            location.reload();
        }
        if(distance > 0) {
            if(days > 0) {
                $('.remaining-time').text(days + " " + "@lang('profile.lang_day')");
            }
            else {
                $('.remaining-time').text(hours + " " + "@lang('profile.lang_hour')" + " " + minutes + " " + "@lang('profile.lang_minutes')" + " " + seconds + " " + "@lang('profile.lang_second')");
            }
        }
        else {
            $('.remaining-time-button').hide();
        }
    }, 1000);
});

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

该代码运行得很好,但是每当我使用来自不同国家的两个浏览器时,它都会给出不同的结果。 (加上3个小时,再加上10个小时..取决于时区)

服务器时区位于亚洲/利雅得。而且,我确实会在用户每次登录时存储用户的时区,但是在这种情况下,我不确定这对我有什么帮助。我正确显示了日期和时间,没有任何问题(相对于时区),但是剩余时间不正确。

javascript laravel time timezone php-carbon
1个回答
0
投票
评论断言不正确。在相同或其他时区为用户做不同的事情无关紧要。您应该给JS带有GMT时区的ISO字符串(如果通过JSON响应发送,则会自动完成。您会得到类似2020-06-30T19:49:03.123Z的字符串,其中Z表示GMT

因此使用:

$dateTime = Carbon::parse($dateTime . ' ' . $book->from)->toJSON();

对于每个用户。因此new Date("{{$dateTime}}");会完全理解这是格林尼治标准时间并将其转换。因此,如果您的JS脚本没有弄乱时区,那么到处都是相同的持续时间。
© www.soinside.com 2019 - 2024. All rights reserved.