Javascript在没有DST的情况下打破时区

问题描述:

I'm trying to set a user's timezone offset for PHP, being sent over ajax. A page has been loaded with session data. If there is no data this gets put into the page:

<script type="text/javascript">
    $(document).ready(function() {
        var visitortime = new Date();
        visitortime.setMonth(1);
        var visitortimezone = visitortime.getTimezoneOffset()*60;
        $.ajax({
            url: "/ajax/timezone/set/"+ visitortimezone,
            success: function(){
               location.reload();
            }
        });
    });
</script>

without the visitortime.setMonth(1); it runs fine and returns the right offset. But with it, it returns only 0.

I want to be able to get timezone offset without DST and then run DST check on the PHP side.

I managed to fix it with this bit of code:

Date.prototype.stdTimezoneOffset = function() {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function() {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

$(document).ready(function() {
    var visitortime = new Date();
    var visitortimezone = visitortime.getTimezoneOffset()*60;

    if(visitortime.dst()){
        visitortimezone = visitortimezone + 60*60;
    }

    $.ajax({
        type: "GET",
        url: "/ajax/timezone/set/"+ visitortimezone,
        success: function(){
            location.reload();
        }
    });
});

Found here: Check if Daylight Saving Time is in effect, and if it is for how many hours.