Create a Date with a set timezone without using a string representation

前端 未结 23 1458
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:48

I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers, then I get a Date obje

23条回答
  •  余生分开走
    2020-11-22 02:18

    This code will return your Date object formatted with the browser timezone.

    Date.prototype.timezone = function () {
        this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
        return this;
    }
    

    Edit:

    To avoid to pollute the Date API, the above function can be transformed into a utility function. The function takes a Date object, and returns a mutated Date object.

    function setTimeZone(date) {
        date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
        return date;
    }
    

提交回复
热议问题